Pseudo-classes and Pseudo-elements


Pseudo-Classes and Pseudo-Elements in CSS

Pseudo-classes and pseudo-elements allow you to style elements based on their state or add additional styling to specific parts of an element. Here’s a brief overview of each:

Pseudo-Classes

Pseudo-classes style elements based on their state or position in the document. They are prefixed with a colon (:).

1. :hover

  • Applies styles to an element when the mouse is over it.

    a:hover { color: red; }

2. :active

  • Applies styles to an element when it is being activated (e.g., clicked).

    a:active { color: blue; }

3. :focus

  • Applies styles to an element when it has focus (e.g., input fields).

    input:focus { border-color: green; }

4. :visited

  • Applies styles to links that have been visited.

    a:visited { color: purple; }

5. :link

  • Applies styles to links that have not been visited.

    a:link { color: black; }

6. :first-child

  • Selects the first child of its parent.

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

7. :last-child

  • Selects the last child of its parent.

    p:last-child { color: blue; }

8. :nth-child(n)

  • Selects the nth child of its parent. n can be a number, keyword (even, odd), or a formula (2n).

    li:nth-child(2) { background-color: yellow; }

9. :nth-of-type(n)

  • Selects the nth child of its type within its parent.

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

10. :not(selector)

  • Selects elements that do not match the given selector.

    p:not(.special) { color: grey; }

11. :checked

  • Applies styles to checked input elements (e.g., checkboxes, radio buttons).

    input:checked { background-color: green; }

Pseudo-Elements

Pseudo-elements style specific parts of an element. They are prefixed with double colons (::) but a single colon (:) is also supported for compatibility.

1. ::before

  • Inserts content before an element’s content.

    p::before { content: "Note: "; font-weight: bold; }

2. ::after

  • Inserts content after an element’s content.

    p::after { content: " (Read more)"; font-style: italic; }

3. ::first-line

  • Applies styles to the first line of a block-level element.

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

4. ::first-letter

  • Applies styles to the first letter of a block-level element.

    p::first-letter { font-size: 2em; color: red; }

5. ::selection

  • Applies styles to the portion of an element that is selected by the user.

    ::selection { background: yellow; color: black; }