Contenu du cours
CSS Fundamentals
CSS Fundamentals
Structural and Functional Pseudo-Classes
Pseudo-classes allow you to target elements precisely based on their order within a container. Let's explore some of the most commonly used ones.
:first-child
The :first-child
pseudo-class targets an element that is the first child of its parent, regardless of its tag or class name. Let's consider the following example to clarify. We have a set of elements, and for only the first element (the first <li>
element), we want to set its color
property to blue
.
index.html
index.css
We see that the first element was selected, and only for it we change the color
property.
:last-child
The :last-child
pseudo-class targets the last child of its parent, allowing us to modify any of its properties. Let's consider an example to illustrate how we can use this pseudo-class effectively.
index.html
index.css
:nth-child
The :nth-child
pseudo-class allows you to select elements based on their position within a list of siblings. You can start with simple targeting by specifying a number. For example:
index.html
index.css
This will style only the third element in the list.
Advanced :nth-child
For more complex scenarios, you can use the formula an+b
to select multiple elements based on their position. Here's how the formula works:
a
determines the repetition pattern (e.g., every 2nd, 3rd child, etc.);b
sets the starting point or offset for the selection;n
acts as the counter that increments with each iteration, starting at 0.
Let's consider some typical selectors.
Note
We don't need to remember all the selectors. We can always search for it on Google.
:not()
The :not()
pseudo-class targets elements that do not match a specified selector. For instance, :not(p)
would select all elements except for <p>
elements. Let's explore some examples:
index.html
index.css
1. What pseudo class can be used to select first element in the set of elements?
2. What is the nth-child
pseudo-class used for?
3. How does the last-child
pseudo-class work?
Merci pour vos commentaires !