CSS Pseudo-Classes and Pseudo-Elements

Section 7: CSS Pseudo-Classes and Pseudo-Elements

Lesson 1: Pseudo-Classes

Pseudo-classes in CSS allow the styling of elements based on user interaction or their position in the document tree. This lesson covers commonly used pseudo-classes and their applications.

1.1 :hover, :active, :focus

:hover: Styles an element when the user hovers over it.

a:hover {

    color: #ff5733; /* Change text color on hover */

}

:active: Applies styles to an element being activated (clicked).

button:active {

    background-color: #4CAF50; /* Change button color when clicked */

}

:focus: Styles an element that is currently focused.

 

input:focus {

    border: 2px solid #3498db; /* Highlight input on focus */

}


1.2 :nth-child

The :nth-child() pseudo-class selects elements based on their position in the parent element.

Select Every Even Row:

tr:nth-child(even) {

    background-color: #f2f2f2;

}

Select the Third Paragraph:

p:nth-child(3) {

    font-weight: bold;

}


Lesson 2: Pseudo-Elements

Pseudo-elements create and style virtual elements that are not present in the HTML document. This lesson focuses on ::before and ::after pseudo-elements.

2.1 ::before and ::after

::before: Inserts content before the selected element's actual content. 

p::before {

    content: "🌟 ";

}

::after: Inserts content after the selected element's actual content.

blockquote::after {

    content: "— John Doe";

    font-style: italic;

}

Understanding pseudo-classes and pseudo-elements enhances the ability to style elements dynamically and create engaging user interfaces. In the upcoming sections, we'll delve into advanced CSS techniques and real-world applications.