CSS Pseudo-classes

By Codes With Pankaj


CSS pseudo-classes are powerful selectors that allow you to target elements based on their state, position in the DOM, user interaction, or other dynamic conditions. They are essential for adding interactivity and styling elements in ways that are not possible with simple selectors alone. This tutorial will cover the various types of pseudo-classes, how to use them, and provide practical examples.

Table of Contents

  1. What are CSS Pseudo-Classes?

  2. Basic Pseudo-Classes

    • Hover (:hover)

    • Active (:active)

    • Focus (:focus)

  3. Structural Pseudo-Classes

    • First Child (:first-child)

    • Last Child (:last-child)

    • Nth Child (:nth-child)

    • Nth of Type (:nth-of-type)

    • Only Child (:only-child)

  4. State-Based Pseudo-Classes

    • Checked (:checked)

    • Disabled (:disabled)

    • Enabled (:enabled)

  5. Negation Pseudo-Class (:not)

  6. Interactive Pseudo-Classes

    • Visited (:visited)

    • Link (:link)

  7. UI Element States

    • Valid (:valid)

    • Invalid (:invalid)

    • Required (:required)

    • Optional (:optional)

  8. Practical Examples

    • Example 1: Styling Buttons with Hover and Active States

    • Example 2: Using Nth Child for Zebra Striped Tables

    • Example 3: Styling Form Inputs with Focus and Validation States

  9. Best Practices for Using Pseudo-Classes

  10. Conclusion


1. What are CSS Pseudo-Classes?

CSS pseudo-classes are keywords added to selectors that specify a special state of the selected elements. They are used to style elements when they are in a particular state, such as when a user hovers over a link, when an input field is focused, or when a specific child element is targeted.

Syntax:

selector:pseudo-class {
  property: value;
}

Example:

a:hover {
  color: red;
}

Explanation:

  • The pseudo-class :hover is used to style the <a> element when the user hovers over it.


2. Basic Pseudo-Classes

These are some of the most commonly used pseudo-classes, typically associated with user interaction.

a. Hover (:hover)

The :hover pseudo-class applies a style when the user hovers over an element, typically used for links, buttons, or any interactive element.

Example:

button:hover {
  background-color: blue;
  color: white;
}

Use Case:

  • Highlighting buttons or links when hovered to indicate they are interactive.

b. Active (:active)

The :active pseudo-class applies a style to an element during the time it is being clicked.

Example:

button:active {
  background-color: darkblue;
  transform: scale(0.98);
}

Use Case:

  • Providing visual feedback when a button is pressed.

c. Focus (:focus)

The :focus pseudo-class applies a style to an element that has received focus, such as an input field that a user has clicked into.

Example:

input:focus {
  border-color: green;
  outline: none;
}

Use Case:

  • Highlighting form fields when they are selected by the user.


3. Structural Pseudo-Classes

Structural pseudo-classes target elements based on their position within the DOM.

a. First Child (:first-child)

The :first-child pseudo-class applies a style to the first child element of its parent.

Example:

p:first-child {
  font-weight: bold;
}

Use Case:

  • Emphasizing the first paragraph or element within a container.

b. Last Child (:last-child)

The :last-child pseudo-class applies a style to the last child element of its parent.

Example:

p:last-child {
  margin-bottom: 0;
}

Use Case:

  • Removing the margin or padding from the last element in a container.

c. Nth Child (:nth-child)

The :nth-child pseudo-class applies a style to elements based on a formula or specific number.

Example:

li:nth-child(odd) {
  background-color: #f0f0f0;
}

Use Case:

  • Creating zebra-striped lists or tables.

d. Nth of Type (:nth-of-type)

The :nth-of-type pseudo-class is similar to :nth-child, but it only considers elements of a specific type.

Example:

p:nth-of-type(2) {
  color: red;
}

Use Case:

  • Targeting a specific occurrence of an element type within a container.

e. Only Child (:only-child)

The :only-child pseudo-class applies a style to an element that is the only child of its parent.

Example:

div:only-child {
  border: 1px solid #ccc;
}

Use Case:

  • Styling single elements within a container.


4. State-Based Pseudo-Classes

These pseudo-classes target elements based on their state, often used in forms.

a. Checked (:checked)

The :checked pseudo-class applies a style to any checkbox or radio button that is checked.

Example:

input[type="checkbox"]:checked {
  background-color: green;
}

Use Case:

  • Indicating the selected state of checkboxes or radio buttons.

b. Disabled (:disabled)

The :disabled pseudo-class applies a style to elements that are disabled, such as form inputs.

Example:

input:disabled {
  background-color: #e0e0e0;
  cursor: not-allowed;
}

Use Case:

  • Styling disabled form fields to differentiate them from active fields.

c. Enabled (:enabled)

The :enabled pseudo-class applies a style to elements that are enabled and can be interacted with.

Example:

input:enabled {
  border-color: blue;
}

Use Case:

  • Highlighting active form fields or buttons.


5. Negation Pseudo-Class (:not)

The :not pseudo-class allows you to exclude elements from a selection based on a specific condition.

Example:

p:not(.highlight) {
  color: gray;
}

Use Case:

  • Applying styles to all elements except those that match a certain condition.


6. Interactive Pseudo-Classes

These pseudo-classes are commonly used with links to indicate their state.

a. Visited (:visited)

The :visited pseudo-class applies a style to links that have been visited by the user.

Example:

a:visited {
  color: purple;
}

Use Case:

  • Differentiating between visited and unvisited links.

The :link pseudo-class applies a style to links that have not yet been visited.

Example:

a:link {
  color: blue;
}

Use Case:

  • Styling unvisited links differently from visited ones.


7. UI Element States

These pseudo-classes are particularly useful for form validation.

a. Valid (:valid)

The :valid pseudo-class applies a style to form elements that are valid according to the specified validation rules.

**Example

:**

input:valid {
  border-color: green;
}

Use Case:

  • Indicating that a form field meets the validation criteria.

b. Invalid (:invalid)

The :invalid pseudo-class applies a style to form elements that do not meet the validation criteria.

Example:

input:invalid {
  border-color: red;
}

Use Case:

  • Highlighting form fields that fail validation.

c. Required (:required)

The :required pseudo-class applies a style to form elements that are required to be filled out.

Example:

input:required {
  border-color: orange;
}

Use Case:

  • Indicating required form fields.

d. Optional (:optional)

The :optional pseudo-class applies a style to form elements that are optional and do not need to be filled out.

Example:

input:optional {
  border-color: gray;
}

Use Case:

  • Differentiating between required and optional fields in a form.


8. Practical Examples

Let’s explore some practical examples of how to use pseudo-classes effectively.

Example 1: Styling Buttons with Hover and Active States

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Button Hover and Active States - codeswithpankaj</title>
  <style>
    .button {
      padding: 10px 20px;
      background-color: blue;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    .button:hover {
      background-color: darkblue;
    }

    .button:active {
      background-color: navy;
      transform: scale(0.98);
    }
  </style>
</head>
<body>

<button class="button">Click Me</button>

</body>
</html>

Explanation:

  • The button changes color when hovered and provides a slight scale effect when clicked.

Example 2: Using Nth Child for Zebra Striped Tables

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Zebra Striped Table - codeswithpankaj</title>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
    }

    th, td {
      padding: 10px;
      border: 1px solid #ddd;
    }

    tr:nth-child(odd) {
      background-color: #f9f9f9;
    }

    tr:nth-child(even) {
      background-color: #fff;
    }
  </style>
</head>
<body>

<table>
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
    <th>Header 3</th>
  </tr>
  <tr>
    <td>Row 1, Cell 1</td>
    <td>Row 1, Cell 2</td>
    <td>Row 1, Cell 3</td>
  </tr>
  <tr>
    <td>Row 2, Cell 1</td>
    <td>Row 2, Cell 2</td>
    <td>Row 2, Cell 3</td>
  </tr>
  <tr>
    <td>Row 3, Cell 1</td>
    <td>Row 3, Cell 2</td>
    <td>Row 3, Cell 3</td>
  </tr>
</table>

</body>
</html>

Explanation:

  • The table rows alternate in background color, creating a zebra stripe effect for easier readability.

Example 3: Styling Form Inputs with Focus and Validation States

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Form Input Validation - codeswithpankaj</title>
  <style>
    input {
      padding: 10px;
      border: 2px solid #ccc;
      border-radius: 5px;
      transition: border-color 0.3s ease;
    }

    input:focus {
      border-color: blue;
      outline: none;
    }

    input:valid {
      border-color: green;
    }

    input:invalid {
      border-color: red;
    }
  </style>
</head>
<body>

<form>
  <label for="email">Email:</label>
  <input type="email" id="email" required>
</form>

</body>
</html>

Explanation:

  • The input field changes color based on focus and whether the entered value is valid or invalid, providing immediate feedback to the user.


9. Best Practices for Using Pseudo-Classes

When using pseudo-classes, consider the following best practices:

  • Combine Pseudo-Classes: Combine multiple pseudo-classes to target more specific states (e.g., input:focus:invalid).

  • Consider Accessibility: Ensure that your use of pseudo-classes does not hinder accessibility, such as by providing sufficient contrast for focus states.

  • Keep It Maintainable: Use pseudo-classes thoughtfully to avoid overly complex CSS that is difficult to maintain.


10. Conclusion

CSS pseudo-classes are a powerful tool for adding interactivity and dynamic styling to your web pages. By understanding and effectively using pseudo-classes, you can create more engaging and user-friendly designs that respond to user actions, target specific elements, and provide visual feedback.

  • Basic Pseudo-Classes: Control styles based on user interaction like :hover, :active, and :focus.

  • Structural Pseudo-Classes: Target elements based on their position in the DOM, such as :first-child and :nth-child.

  • State-Based Pseudo-Classes: Style elements based on their state, such as :checked, :disabled, and :enabled.

  • Interactive Pseudo-Classes: Manage link states with :visited and :link.

  • UI States: Use :valid, :invalid, :required, and :optional for form validation and user input.

By applying these pseudo-classes effectively, you can enhance the functionality and aesthetics of your web designs.


For more tutorials and insights, visit Codes With Pankaj.

Last updated