Combining Selectors
Updated Mar 20, 2019 ·
Overview
Different CSS selectors apply styles to various elements based on their type, position, or interaction.
The examples below use the following HTML file:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button>Click Me</button>
<input type="text" placeholder="Type here">
<p>Paragraph with default color.</p>
<div>
<p>Direct paragraph inside div</p>
<section>
<p>Nested paragraph inside section</p>
</section>
</div>
<div>
<h2>This is an H2 header</h2>
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
<h2>This is another H2 header</h2>
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
<li>Fourth item</li>
</ul>
</div>
</body>
</html>
Grouping Selectors
The same rule can apply to multiple elements using a comma.
button, p {
color: blue;
}
- Selects both h1 and h2
- Applies the same style to both
This is useful for reducing repetitive code.
Descendant Selector (Space)
This rule targets elements nested within a specific ancestor.
div p {
color: red;
}
- Selects all
<p>elements inside<div>. - Works regardless of nesting depth
Use this when styling all occurrences of an element within a parent.
Child Selector (>)
The > selector targets only direct children, ignoring nested ones.
div > h2 {
color: green;
}
/* Only applies to direct <p> inside <div>, not nested ones */
div > p {
font-style: italic;
}
Note:
- In the
<ul>, only top-level<li>elements are green- Sub-items remain unaffected
- In the
<div>, only the direct<p>is italic- Nested
<p>inside<section>is unaffected
- Nested
Use this to style only immediate child elements.