Structural pseudo-classes allow you to target elements based on their position within the document structure. They can be useful for creating responsive layouts and applying specific styles to elements based on their context.
Common Structural Pseudo-Classes
- :root: Targets the root element of the document (usually the <html> element).
- :first-child: Targets the first child element of its parent.
- :last-child: Targets the last child element of its parent.
- :nth-child(n): Targets the nth child element of its parent, where n is a number.
- :nth-of-type(n): Targets the nth element of its type within its parent.
- :only-child: Targets an element that is the only child of its parent.
- :first-of-type: Targets the first element of its type within its parent.
- :last-of-type: Targets the last element of its type within its parent.
- :only-of-type: Targets an element that is the only element of its type within its parent.
Example
HTML
<div class=”container”>
<div class=”item”>Item 1</div>
<div class=”item”>Item 2</div>
<div class=”item”>Item 3</div>
</div>
CSS
.container:first-child
{
background-color: #f0f0f0;
}
.item:nth-child(odd) {
background-color: #eee;
}
.item:last-of-type {
font-weight: bold;
}
Using Structural Pseudo-Classes in Responsive Design
Structural pseudo-classes can be combined with media queries to create responsive layouts. For example, you can use :nth-of-type to target specific elements within a grid layout based on their position.
Example
CSS
@media only screen and (max-width: 600px) {
.container {
display: flex;
flex-direction: column;
}
.item:nth-of-type(1) {
background-color: #f0f0f0;
}
} Structural pseudo-classes provide a powerful way to target elements based on their position within the document structure. By understanding and effectively using these selectors, you can create more targeted and responsive stylesheets for your web designs.