1.1 Pseudo-classes
Pseudo-classes in CSS are special keywords added to selectors to specify their state or position in the document tree. They let you style elements based on their state or relation to other elements without needing to add classes or IDs to the HTML code.
Main Concepts of Pseudo-classes
- Defining the state of an element:
- Pseudo-classes can indicate the state of an element, like mouse hover, focus, or activation.
- Defining the position of an element:
- Pseudo-classes can indicate an element's position relative to its parent or other elements, such as first or last element.
- Special cases and logical groups:
- Pseudo-classes can also define special cases, like first of type or odd/even element.
How to Use Pseudo-classes
Pseudo-classes are added to a selector using a colon (:). They can be used with element selectors, as well as with classes, IDs, and other selectors.
Syntax:
selector:pseudo-class {
properties: values;
}
Usage Examples
1. Element Selector with Pseudo-class
In this example, all first paragraphs (<p>
) within their parent elements will be bold:
p:first-of-type {
font-weight: bold;
}
2. Class Selector with Pseudo-class
In this example, the background of all elements with the .button
class will turn blue when the mouse hovers over them:
.button:hover {
background-color: blue;
}
3. Combined Selectors with Pseudo-classes
In this example, all even paragraphs (<p>
) inside elements with class .container
will be red:
.container > p:nth-child(2n) {
color: red;
}
1.2 Examples of Pseudo-classes and Their Application
1. State-defining Pseudo-classes
State-defining pseudo-classes allow you to change the styling of an element based on user interaction or the element's state.
a:link {
color: blue;
}
a:visited {
color: purple;
}
a:hover {
color: red;
}
a:active {
color: green;
}
2. Position-defining Pseudo-classes
Position-defining pseudo-classes allow you to apply styles to elements based on their location in the DOM structure.
li:first-child {
font-style: italic;
}
li:last-child {
font-style: italic;
}
li:nth-child(odd) {
background-color: #f0f0f0;
}
li:nth-child(even) {
background-color: #ffffff;
}
3. Pseudo-classes for Logical Groups
These pseudo-classes allow you to style elements based on their logical groups or types.
input:checked {
background-color: yellow;
}
input:disabled {
background-color: grey;
}
input:enabled {
background-color: white;
}
GO TO FULL VERSION