5.1 Types of Selectors
Combined selectors in CSS let you target elements based on their relative position in the DOM tree. They give you more precise control over styling, allowing you to style elements based on their context. There are several types of combined selectors in CSS: descendant, child, adjacent sibling, and general sibling.
Types of combined selectors:
- Descendant Selector
- Child Selector
- Adjacent Sibling Selector
- General Sibling Selector
5.2 Descendant Selector
The descendant selector targets all elements that are descendants of a specified element. Descendants include any elements contained within the specified element at any level of nesting (not just children, but also grandchildren, great-grandchildren, and so on).
Syntax:
ancestor descendant {
property: value;
property: value;
}
Example:
/* Selects all <p> elements inside a <div> */
div p {
color: blue;
}
<div>
<p>This paragraph will be blue.</p>
<div>
<p>This paragraph will also be blue because it's a descendant of "div".</p>
</div>
</div>
<p>This paragraph will not be blue.</p>
5.3 Child Selector
The child selector selects only those elements that are direct children of a specified parent.
Syntax:
parent > child {
property: value;
property: value;
}
Example:
/* Selects only <p> elements that are direct children of .container */
.container > p {
color: green;
}
<div class="container">
<p>This paragraph will be green.</p>
<div class="wrapper">
<p>This paragraph won't be green because it's not a direct child of .container.</p>
</div>
<p>This paragraph will be green.</p>
</div>
<p>This paragraph will not be green.</p>
5.4 Adjacent Sibling Selector
The adjacent sibling selector selects an element that directly follows a specified element and is on the same level of nesting.
Syntax:
previous + next {
property: value;
property: value;
}
/* Selects <p> that directly follows <h1> */
h1 + p {
color: red;
}
<h1>Heading 1</h1>
<p>This paragraph will be red because it directly follows "h1".</p>
<p>This paragraph will not be red.</p>
5.5 General Sibling Selector
The general sibling selector selects all elements that follow a specified element and are on the same level of nesting.
Syntax:
previous ~ next {
property: value;
property: value;
}
Example:
/* Selects all <p> elements that follow <h1> on the same nesting level */
h1 ~ p {
color: purple;
}
<h1>Heading 1</h1>
<p>This paragraph will be purple.</p>
<p>This paragraph will also be purple.</p>
<div>
<p>This paragraph won't be purple because it's at a different nesting level.</p>
</div>
GO TO FULL VERSION