Pseudo-classes in CSS: Selecting and Styling Specific Element States


In CSS, pseudo-classes are used to select and style elements based on specific states or conditions. Pseudo-classes allow you to target elements that cannot be selected based on their HTML structure alone. They provide a way to style elements in response to user interactions, element states, or their position within a document.

Here are some commonly used pseudo-classes and their explanations:

  1. :hover: Targets an element when the mouse pointer is over it. It is commonly used to change the appearance of elements on mouse hover.
  2. :active: Targets an element when it is being activated, such as when a mouse button is pressed on it. It is often used to provide visual feedback during user interactions.
  3. :focus: Targets an element when it receives focus, such as when it is selected using the keyboard or by clicking on it. It is commonly used to style form elements or interactive components.
  4. :visited: Targets an <a> (anchor) element that has been visited by the user. It allows you to apply different styles to visited and unvisited links.
  5. :nth-child(n): Targets elements based on their position within their parent element. It selects the nth child element that matches the specified pattern. For example, :nth-child(odd) selects all odd-numbered elements.
  6. :first-child: Targets the first child element of its parent. It allows you to apply specific styles to the first element in a container.
  7. :last-child: Targets the last child element of its parent. It allows you to style the last element in a container differently.
  8. :not(selector): Targets elements that do not match the specified selector. It provides a way to exclude certain elements from a selection.
  9. :checked: Targets an input element (checkbox or radio button) that is checked. It is often used to style the appearance of checked elements.
  10. :target: Targets the element that is currently being targeted by a URL fragment identifier. It is useful for creating scroll-to-anchor functionality.
  11. :before and :after: Allows you to insert content before or after an element's content, respectively. It is commonly used to add decorative elements or icons to elements.

Pseudo-classes extend the selectors in CSS and provide additional flexibility for styling elements based on specific conditions or states. By utilizing pseudo-classes, you can enhance user experience, create interactive effects, and style elements dynamically in response to various events and states.

root

In CSS, the :root selector is a pseudo-class that targets the root element of the document, which is typically the <html> element. It allows you to apply styles to the root element or define CSS custom properties that can be accessed and used throughout the document.

Here are a couple of use cases for the :root selector:

:root{
  --bgcolor:aliceblue;
  --color:teal;
}
h1{
  color:var(--color);
}
p{
  padding: 10px;
  background-color:var(--bgcolor);
  color:var(--color);
}
Live Preview

The :root selector is typically placed at the top of the CSS file or within a CSS block to define global styles or variables. It is supported in all modern web browsers.

It's important to note that the :root selector specifically targets the root element of the document (usually the <html> element) and should not be confused with the root pseudo-class used in certain CSS preprocessors like Sass, which refers to the current selector's parent.

First Child

In CSS, the :first-child and :last-child selectors are used to target specific elements based on their position within their parent element.

The :first-child selector matches an element that is the first child of its parent. It selects an element only if it's the first child among its siblings. Here's an example of how to use it:

#list-1 li:first-child{
  color:blue;
}

p:first-child{
  color:orangered;
}

Last Child

In CSS :last-child selector matches an element that is the last child of its parent. It selects an element only if it's the last child among its siblings. Here's an example of how to use it:

li:last-child{
    color:red;
}

p:last-child{
   color:brown;
   font-weight: bold;
}

nth-child

In CSS, the :nth-child() selector is used to select elements based on their position among their siblings within the same parent element. It allows you to target elements using a formulaic pattern.

The :nth-child() selector takes a formula as its argument, which can be an explicit number, a keyword, or a mathematical expression.

#l1 li:nth-child(5){
  color:red;
  font-weight: bold;
}
/*
    n=0,1,2,3,4
    2n
      2*0=0
      2*1=2
      2*2=4
      2*3=6
    2n+1
      (2*0)+1=1
      (2*1)+1=3
      (2*2)+1=5
      (2*3)+1=7
    3n-1
      (3*0)-1=0
      (3*1)-1=2
      (3*2)-1=5
      (3*3)-1=8
*/
#l2 li:nth-child(3n-1){
  color:navy;
  font-weight: bold;
}

The :nth-child() selector provides a powerful way to target elements based on their position within their parent element. It allows you to apply specific styles to elements in a repeating pattern or select elements within a certain range. The formulaic pattern can be customized to match your specific requirements.

nth-last-child

In CSS, the :nth-last-child() selector is used to select elements based on their position among their siblings within the same parent element, counting from the last child towards the first child.

Similar to the :nth-child() selector, the :nth-last-child() selector also takes a formula as its argument, which can be an explicit number, a keyword, or a mathematical expression.

#l2 li:nth-last-child(5){
    color:orange;
    font-weight: bold;
}

The :nth-last-child() selector provides a way to target elements based on their position counted from the last child of their parent element. It allows you to apply specific styles to elements in a repeating pattern or select elements within a certain range, but counting from the end rather than the beginning.

Live Preview

nth-of-type

In CSS, the :nth-of-type() selector is used to select elements based on their position among siblings of the same element type within the same parent element. It allows you to target elements using a formulaic pattern specific to their type.

The :nth-of-type() selector takes a formula as its argument, which can be an explicit number, a keyword, or a mathematical expression.

p:nth-of-type(1){
    color:red;
}
li:nth-of-type(1){
    color:red;
}
.l2 li:nth-of-type(odd){
    color:purple;
}
.l2 li:nth-of-type(even){
    color:green;
}

The :nth-of-type() selector provides a powerful way to target elements based on their position among siblings of the same type within their parent element. It allows you to apply specific styles to elements in a repeating pattern or select elements within a certain range, but specifically based on their type.

nth-last-of-type

In CSS, the :nth-last-of-type() selector is used to select elements based on their position among siblings of the same type within the same parent element, counting from the last element of that type towards the first element.

Similar to the :nth-of-type() selector, the :nth-last-of-type() selector also takes a formula as its argument, which can be an explicit number, a keyword, or a mathematical expression.

p:nth-last-of-type(1){
    color:blue;
}
li:nth-last-of-type(1){
    color:blue;
}

The :nth-last-of-type() selector allows you to target elements based on their position among siblings of the same type within their parent element, counting from the last element of that type. It provides a way to apply specific styles to elements in a repeating pattern or select elements within a certain range, but counting from the end rather than the beginning.

Live Preview

only-child

In CSS, the :only-child selector is used to target elements that are the only child of their parent. It selects an element only if it's the only child among its siblings.

li:only-child{
  color:red;
}

The :only-child selector is useful when you want to style elements that are the sole child of their parent, without any siblings. It can be used to target and apply specific styles to elements that have a unique position within their parent container.

It's important to note that elements targeted by :only-child must not have any preceding or subsequent sibling elements within the same parent. If there are multiple elements of the same type as siblings, the :only-child selector won't select any of them.

Live Preview

only-of-type

In CSS, the :only-of-type selector is used to target elements that are the only sibling of their type within the same parent element, regardless of whether they have other non-matching sibling elements. It selects an element only if it's the only one of its type among its siblings.

p:only-of-type{
    color: brown;
}

The :only-of-type selector is useful when you want to style elements that are the sole sibling of their type within their parent container, regardless of the presence of other sibling elements of different types. It allows you to target and apply specific styles to elements that have a unique position among their sibling elements of the same type within their parent.

It's important to note that the :only-of-type selector focuses on elements that are the only sibling of their specific type, and it disregards sibling elements of different types. If there are multiple elements of different types as siblings, the :only-of-type selector won't select any of them.

Therefore, the :only-of-type selector is useful when you specifically want to target and style elements that are the sole element of their type among their siblings, regardless of the presence of other non-matching sibling elements.

Live Preview

first-of-type

In CSS, the :first-of-type selector is used to target the first element of its type among its siblings within the same parent element. It selects an element only if it's the first among its siblings of the same type.

li:first-of-type{
    color:red;
}
p:first-of-type{
    color:red;
}

The :first-of-type selector is useful when you want to style the first element of a specific type among its sibling elements. It allows you to apply specific styles to the first occurrence of an element type within its parent container.

It's important to note that the :first-of-type selector focuses on elements of the same type within their parent and identifies the first occurrence of that type. If there are multiple elements of different types as siblings, the :first-of-type selector won't select any of them unless they are the first of their respective types.

Therefore, the :first-of-type selector is useful when you specifically want to target and style the first occurrence of a certain element type among its siblings within its parent container.

last-of-type

In CSS, the :last-of-type selector is used to target the last element of its type among its siblings within the same parent element. It selects an element only if it's the last among its siblings of the same type.

li:last-of-type{
    color:green;
}
p:last-of-type{
    color:green;
}

The :last-of-type selector is useful when you want to style the last element of a specific type among its sibling elements. It allows you to apply specific styles to the last occurrence of an element type within its parent container.

It's important to note that the :last-of-type selector focuses on elements of the same type within their parent and identifies the last occurrence of that type. If there are multiple elements of different types as siblings, the :last-of-type selector won't select any of them unless they are the last of their respective types.

Therefore, the :last-of-type selector is useful when you specifically want to target and style the last occurrence of a certain element type among its siblings within its parent container.

Live Preview

empty

In CSS, the :empty pseudo-class selector is used to target elements that have no children or contain no content. It selects elements that do not have any child elements or text content.

p:empty{
  padding: 10px;
  border: 2px solid goldenrod;
}
Live Preview

The :empty selector is useful when you want to style elements that are empty or have no content. It allows you to apply specific styles to elements that do not contain any text or child elements.

It's important to note that elements targeted by :empty must not have any content, including spaces or line breaks. If an element contains even a single whitespace character or line break, it will not be considered empty and will not be selected by :empty.

Additionally, the :empty selector only targets elements that have no child elements or content directly within them. It does not check whether an element has any descendant elements or content within those descendants.

Therefore, the :empty selector is useful when you specifically want to target and style elements that have no child elements or content within them.

not

In CSS, the :not() selector is a powerful pseudo-class that allows you to select elements that do not match a specific selector. It is used to exclude certain elements from a selection.

The :not() selector takes a parameter, which is a selector representing the elements to be excluded.

p:not(.para){
  color:red;
}
Live Preview

lang

In CSS, you can target elements based on the lang attribute using the attribute selector. The lang attribute is used to specify the language of the content within an element.

p:lang(fr){
    color:blueviolet;
}
p:lang(en){
    color:red;
}

In this case, the first <p> element with lang="fr" will have its text color set to blueviolet because it matches the p:lang(fr) selector. The second <p> element with lang="en" will have its text color set to red because it matches the p:lang(en) selector. The third <p> element without a lang attribute will not match either selector and will retain its default text color.

So, the CSS code is defining different text colors for paragraphs based on the value of their lang attribute, allowing for language-specific styling.

<p lang="en">computer an electronic machine that can store, find and arrange information, calculate amounts and control other machines.</p>

<p lang="fr">ordinateur une machine électronique capable de stocker, de trouver et d'organiser des informations, de calculer des montants et de contrôler d'autres machines.</p>

<p lang="en">Tutor Joes</p>
Live Preview

The first and third <p> elements will have their text color set to red because they have lang="en", which matches the p:lang(en) selector. The second <p> element will have its text color set to blueviolet because it has lang="fr", which matches the p:lang(fr) selector.

Anchor

In CSS, the pseudo-element ::before and ::after are commonly used to add content before or after an element's actual content. However, there is no specific pseudo-element for anchor tags (<a> tags). Instead, you can apply pseudo-classes to style different states of anchor elements, such as :hover, :visited, :active, and :focus.

a:link{
    color:green;
}
a:hover{
    background-color: teal;
    color:white;
}
a:active{
    color:orangered;
}
a:visited{
    color:darkred;
}
Live Preview

The :hover pseudo-class changes the color to red when the link is hovered. The :visited pseudo-class sets the color to purple for visited links. The :active pseudo-class changes the color to green when the link is actively clicked. The :focus pseudo-class applies an outline style when the link is focused, typically via keyboard navigation.

These pseudo-classes allow you to style different states of anchor tags to enhance the user experience and provide visual feedback to users.

:target

In CSS, the :target pseudo-class is used to select and style an element that is the target of the current URL's fragment identifier (the part of the URL that follows the "#" symbol).

The :target pseudo-class is useful when creating navigation or tabbed content where clicking on a link changes the displayed content within the same page.

p:target{
      background-color: aquamarine;
      color:blue;
}
Live Preview

Form

In CSS, there is no specific pseudo-element for <form> tags. However, you can use pseudo-classes to target and style different states or elements within a <form>.

Here are some commonly used pseudo-classes for styling forms:

  • :valid and :invalid: These pseudo-classes target form elements that have valid or invalid values based on their defined validation rules.
  • :focus: This pseudo-class targets form elements that currently have keyboard focus.
  • :disabled: This pseudo-class targets form elements that are disabled.
  • :checked: This pseudo-class targets checked radio buttons and checkboxes.
  • :placeholder-shown: This pseudo-class targets form elements whose placeholder text is currently shown.
  • :required: This pseudo-class targets required form elements.
#t1:focus{
  outline: none;
  border: 1px solid brown;
}
input[type="checkbox"]:checked{
    box-shadow: 0 0 0 3px red;
}
input[type="text"]:enabled{
    background-color: pink;
}
input[type="text"]:disabled{
    background-color: red;
}
input[type="text"]:required{
    background-color: green;
}

input[type="email"]:read-only{
    background-color: gray;
}
input[type="email"]:read-write{
    background-color: plum;
}

input[type='text']:invalid{
     border-color: red;
  }
input[type='text']:valid{
    border-color: green;
}

input[type='radio']:default{
    box-shadow: 0 0 0 3px green;
}

option:default{
    color:red;
}
Live Preview

Remember that the availability and compatibility of certain pseudo-classes may vary across different browsers, so it's important to test your styles across various environments.

:is

In CSS, the :is() pseudo-class function is a powerful selector that allows you to group multiple selectors together and apply styles if any of the selectors match an element. It provides a way to simplify and optimize CSS selectors.

The :is() function takes one or more selectors as arguments and returns true if any of the selectors match the element. It is especially useful when you want to apply the same styles to different selectors without duplicating the styles.

:is(#d1,#d2) h2{
  color:green;
}
Live Preview

The :is() pseudo-class function is supported in modern browsers. However, it's important to note that it might not be supported in older or less common browsers. Therefore, if you're using :is() in your CSS code, it's a good practice to provide a fallback or alternative styles for unsupported browsers, if necessary.

Source Code

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Tutor Joes</title>
    <style>
    a{
	text-decoration: none;
    }
    a:hover{
	color:red;
    }
    a:active{
      color:orange;
    }
    a:visited{
      color:pink;
    }
    </style>
  </head>
  <body>
    <h1>Pseudo Class In CSS</h1>
	<a href="01_inline.html" title="link1">Link-1</a>
	<a href="02_internal.html" title="link2">Link-2</a>
	<a href="03_external.html" title="link3">Link-3</a>
	<a href="04_font.html" title="link4">Link-4</a>
  </body>
</html>
Live Preview
  1. a { text-decoration: none; }: This rule targets all <a> elements and sets the text-decoration property to none. It removes the default underline typically applied to anchor links, resulting in anchor links without any text decoration.
  2. a:hover { color: red; }: This rule targets <a> elements when the mouse pointer is hovering over them. It changes the color property to red, causing the text of the anchor links to appear in red color when hovered.
  3. a:active { color: orange; }: This rule targets <a> elements when they are in an active state, such as when they are being clicked or activated. It changes the color property to orange, resulting in the text of the anchor links appearing in orange color when activated.
  4. a:visited { color: pink; }: This rule targets <a> elements that have been visited by the user. It changes the color property to pink, allowing the text of visited anchor links to appear in pink color.

These styles provide visual feedback to users, making the anchor links more interactive and indicating different states of interaction, such as hover, active, and visited.

CSS Tutorial


Properties Reference


Cascading Style Sheet


Flexbox Tutorial


CSS Grid Tutorial


Transitions Properties


CSS Properties with Examples


CSS Selectors


CSS Pseudo Elements


CSS Attribute Selectors


Input Pseudo Classes


CSS Examples


CSS Animation Projects