CSS Combinator Selectors
CSS combinator selectors enable you to target web elements based on their relationships to other elements within the HTML structure. The main types of combinator selectors are:
1. Descendant Selector
The descendant selector targets elements that are nested within a specified parent element, no matter how deep the nesting. The syntax is parent child. For example:
<!DOCTYPE html>
<html>
<body>
<div class="container">
<p>This is my first paragraph.</p>
<div>
<p>This is my second paragraph.</p>
</div>
</div>
</body>
</html>
In this example, the .container p selector will target both paragraph (<p>) elements inside the .container div, including the nested one.
2. Child Selector
The child selector targets only the direct (immediate) children of a specified parent element. It does not include nested descendants. The syntax is parent > child. For example:
<!DOCTYPE html>
<html>
<body>
<div class="container">
<p>This is my first paragraph.</p>
<div>
<p>This is my second paragraph.</p>
</div>
</div>
</body>
</html>
Here, the .container > p selector will only target the first paragraph (<p>) because it is a direct child of the .container div.
3. Adjacent Sibling Selector
The adjacent sibling selector targets the element immediately following a specific element, provided both share the same parent. The syntax is sibling1 + sibling2. For example:
<!DOCTYPE html>
<html>
<body>
<h1>This is my heading.</h1>
<p>This is my first paragraph.</p>
<p>This is my second paragraph.</p>
</body>
</html>
In this case, the h1 + p selector will target only the first paragraph (<p>) directly following the heading (<h1>), ignoring the second paragraph.
4. General Sibling Selector
The general sibling selector targets all sibling elements that follow a specified element and share the same parent. Unlike the adjacent sibling selector, it applies to all matching siblings. The syntax is sibling1 ~ sibling2. For example:
<!DOCTYPE html>
<html>
<body>
<h1>This is my heading.</h1>
<p>This is my first paragraph.</p>
<p>This is my second paragraph.</p>
</body>
</html>
Here, the h1 ~ p selector will select both paragraph (<p>) elements that follow the heading (<h1>).