CSS Pseudo Classes

Introduction

HTML is used for structuring the content of a webpage, and CSS or Cascading Style Sheets is used for styling the content of a webpage. Without CSS, every web page will be plain text, and images will flow straight down the page. With CSS, one can add color, apply height and width properties, apply animations and create attractive layouts.

 

If you are starting with CSS, you must check out this blog.

 

In this blog, we will discuss Pseudo Classes in CSS. Various Pseudo Class selectors are discussed in detail, along with examples.

An Introduction to CSS Pseudo Class

According to MDN docs, A CSS pseudo-class is a keyword added to a selector that specifies a particular state of the selected element(s). For example, a hover can change a button's color when the user's pointer hovers over it. In simple words, CSS Pseudo Classes are used to add special effects to CSS selectors. They are used to define a particular state of an element, which means the design can react to user input.

 

Syntax of pseudo classes is:

selector:pseudo-class {

  property: value;;

}

 

There are many pseudo-classes selectors. This blog will discuss a few of them with code samples.

 

Link related CSS Pseudo Class selectors

A website usually contains a navigation bar that contains links to different web pages, and in addition, there are many redirect links in a single webpage as well. All the links respond differently to state changes. They might be blue when the user does not click them, might turn red when the mouse cursor rolls over a link, and might turn yellow when the user has already visited them. The various events, i.e., not visited, hovering, visited, and active, are various states to which we can apply different styling or CSS such that the webpage looks more interactive. Let us look at the various link-related pseudo-class selectors one by one:

 

  • Link link selector is a pseudo-class that targets all unvisited anchor (<a>) elements on a page. This will target all the <a> elements with an href attribute, even if the href has an empty value. Since :link can only target <a> elements, :link styles may be defined in the CSS without the element type selector.

 

  • :visited - This selector is used to select the links that the user has already visited. The purpose is to help the user distinguish between the links that have and have not been visited. The following properties can be changed with :visited.
    • color
    • background-color
    • border-color
    • outline-color

 

  • :hover: - When the mouse hovers over a link, that link is considered to be in a :hover state, and this selector will select that link. In IE6 and below versions, hover only works on links, but it works on any elements in newer browsers.

 

  • :active - The :active selector is used for selecting and styling the active link; a link is in an active state when you click on it. This selector can also be used on all elements.

 

Example:

 

HTMLCSS

<h1> Coding Ninjas</h1>

<section class="links">

    <p><a href="https://www.codingninjas.com/" class="link1">This link goes to Coding Ninjas, after its been visited, it will turn gray</a></p>

    <p><a href="https://www.codingninjas.com/codestudio" class="link2">This link goes to Codestudio, after it has been hovered on, it will be green in color and an underline</a></p>

<p><a

href="https://www.codingninjas.com/codestudio/guided-paths" class="link3">This link goes to the guided path and when its active the font-size will be 32px</a></p>

</section>

 

body {

    font-family: system-ui;

    text-align: center;

}

h1 {

    color: blue;

    font-size: 26vh;

}

:link {

    color: orange;

}

a.link1:visited {

    color: gray;

}

a.link2:hover {

    color: green;

    text-decoration: underline overline;

}

 

a.link3:active {

    font-size: 32px;

}

 

 

The corresponding web page looks like this:

 

 

Remember that in the CSS definition, the order of CSS selectors should be: link, visited, hover, active. A yet funny way to remember the sequence is to remember the sequence LOVHATE or LVHA.

 

Link and Input-related CSS Pseudo Class selectors.

Now let’s see the CSS Pseudo Classes related to inputs and links.

 

  1. :enabled - This pseudo-class in CSS is used to select focusable elements that are not disabled. Note that it is only associated with form elements, namely, <input>, <select>, <textarea>. 
  2. :disabled - This pseudo-class in CSS is used to select the inputs that have the disabled attribute. Elements that can receive the disabled attribute include <button>, <input>, <textarea>, <optgroup>, <option> and <fieldset>.

 

Let's look at the following HTML and CSS code snippets to understand the:enabled and :disabled attributes. There is a form with two input fields; the second input field is marked disabled. In the CSS file, the input field with a disabled attribute is given a background color of sky blue and the one which is enabled is given a background color of yellow.

HTMLCSS

<form action="#">

  <label for="name">I am an Enabled Input:</label>

  <input type="text" autofocus>

  <hr>

  <label for="name">I am a Disabled Input:</label>

  <input type="text" disabled>

</form>

body {

  background: cornflowerblue;

}

 

form {

  padding: 1.8rem;

  outline: 3px solid rgba(0, 0, 0, 0.25);

  background-color: whitesmoke;

}

 

input {

  width: 70%;

  margin: 0;

  border: none;

  outline: 1 px solid lightgrey;

  outline-offset: 2px;

}

 

input:disabled {

  background-color: skyblue;

}

 

input:enabled {

  background-color: yellow;

}

 

 

The corresponding web page looks like

 

3) :focus - This selector is used to select the focus element or is currently targeted by the keyboard or activated by the mouse.

 

Consider the below example wherein there is an HTML textarea filled with some random text. The corresponding CSS file uses the pseudo-class selector :focus and turns the background color of the textarea to orange when it’s targeted by the keyboard or is currently focussed on.

HTMLCSS
<textarea placeholder="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sed risus ultricies tristique nulla aliquet enim. Cursus mattis molestie a iaculis."></textarea>

 

textarea:focus{

  background: orange;

  color: white;

}

 

 

The corresponding webpage looks like

 

4) :checked - This pseudo-class is used to select CSS elements that are in the selected state. It is only associated with <input> elements of type radio and checkbox.

 

5) :required - This selector is used to select form elements that are required. The form elements that have a required attribute are defined as required. Using these forms can easily indicate which fields must have valid data before the form can be submitted.

 

The below example illustrates :checked and :required pseudo class selector.

HTMLCSS

<form action="">

 

  <!--! To illustrate :required and : checked pseudo-class selector

-->

  <label>Email</label>

  <input type="email" required />

  <hr>

  <input type="checkbox" id="ossm" name="ossm">

  <label for="ossm">CSS is Awesome</label>

 

</form>

 

form {

  padding: 20px;

  max-width: 500px;

  margin: 0 auto;

}

 

input {

  border: 1px solid #999;

  padding: 5px;

}

input[type="checkbox"] + label {

  color: #ccc;

  font-style: italic;

}

input[type="checkbox"]:checked + label {

  color: #f00;

  font-style: normal;

}

 

input:required {

  border-color: red;

}

 

 

 

Position/Number based CSS Pseudo Class Selectors.

  1. :root -  The :root selector allows you to target the highest-level "parent" element in the DOM, or document tree. While the :root selector and html selector both target the same HTML elements, it is interesting to note that :root has a higher specificity.
  2. :first-child - The :first-child selector is used for selecting the specified selector, only if it is the first child of its parent. As defined in the CSS selector Level 3 specification. It is a structural pseudo-class meaning it is used to style the content based on its relationship with the parent and siblings.
  3. :last-child - The :last-child selector allows you to target the last element directly inside its containing element.  It is also a structural pseudo-class.

 

Likewise, there are :nth-child(), :nth-of-type(), :first-of-type(),:last-of-type() and other pseudo class selectors as well.  The following example uses all the commonly used position based pseudo class selectors.

HTMLCSS

<article>

  <p>First paragraph...</p>

  <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient monte</p>

  <p>Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu </p>

  <p> Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel nunc,</p>

</article>

 

<ul>

  <li>First Item</li>

  <li>Second Item</li>

  <li>Third Item</li>

  <li>Fourth Item</li>

  <li>Fifth Item</li>

</ul>

 

:root{

  background-color: cornflowerblue;

  font-family: Arial, sans-serif;

}

 

p:first-child{

  color: white;

}

 

p:last-child{

  color: red;

}

 

p:nth-child(1){

  background-color: black;

}

 

li{

  background: slategray;

  width: 50%;

  padding: 10px;

  align-items: center;

}

 

li:nth-of-type(2n + 1){

  background: white;

}

 

li:first-of-type{

  font-size: 22px;

}

 

li:last-of-type{

  font-size: 22px;

}

 

li:nth-last-of-type(3){

  background-color: pink;

}

 

 

The webpage looks like this:

 

You must refer to the below image for a better understanding of CSS position-based pseudo-class selectors.

 

(Source: css-tricks.com)

 

Relational CSS Pseudo Class Selectors

  1. :not The :not()  pseudo-class represents elements that do not match a list of selectors. Since it prevents specific items from being selected, it is also known as the negation pseudo-class. This requires a comma-separated list of one or more selectors as its argument.

 

HTML CSS

<h1>This is a heading</h1>

 

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

 

<div>This is some text inside a div element.</div>

 

<a href="https://www.codingninjas.com/codestudio">Link to Coding Ninjas</a>

 

:root{

  background-color: lightgray;

}

p{

  color: red;

}

 

:not(p){

  color: green;

}

 

 

The corresponding web page looks like

  

  1. :empty - The CSS :empty pseudo-class selects any element that does not contain children for a given selector.

 

HTMLCSS

<!--Empty div element-->

<div></div>

<!--Empty h2 element-->

<h2></h2>

:root {

  background-color: lightgray;

}

 

div:empty{

  height: 100px;

  background-color: tomato;

}

h2:empty{

  height: 55px;

  background-color: yellow;

}

 

The corresponding webpage looks like this:

 

Content Related Pseudo Elements

  1. ::before and ::afterThe :: before and ::after pseudo-elements in CSS allow you to insert content onto a page without needing to be in the HTML. While the end result is not actually in the DOM, it appears on the page as if it is and would essentially be like this.

 

HTMLCSS

<div>

  <p>Paragraph 1</p>

  <p>Paragraph 2</p>

</div>

 

div::before {

  content: "Text inside CSS before selector";

  color: red;

}

div::after {

  content: "Text inside CSS after selector";

  color: green;

}

 

div{

  font-size: 34px;

}

 

The corresponding web page looks like

 

 

You must refer to this for more details.

Frequently Asked Questions

Q1) What are CSS Pseudo Classes?
Ans 1) A CSS pseudo-class is a keyword added to a selector that specifies a particular state of the selected element(s). For example, a visit can change a button's color when the user has already visited a link.

Q2) What is CSS Pseudo Elements?
Ans 2) A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected element(s). For example, ::first-line can be used to change the font of the first line of a paragraph.

 

Key Takeaways

This blog covers the various types of CSS Pseudo Selectors. At the end of the blog, some of the frequently asked questions related to CSS Pseudo Classes have also been discussed.

Frontend developers, if you are preparing for the next interview, check out the blogs 25 CSS Interview Questions For Beginners in 2021: Part 1 and 25 CSS Interview Questions for Experienced in 2021: Part 2. And if you are a beginner, check out the 10 Best HTML & CSS books for developers in 2021 to learn HTML and CSS from scratch.

Planning to ace the interviews of reputed product-based companies like Amazon, Google, Microsoft, and more? Attempt our Online Mock Test Series on CodeStudio now!

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think