CSS Combinators
CSS combinators define the relationship between selectors, allowing you to style elements based on their hierarchy and structure. There are four main types of combinators: descendant, child, adjacent sibling, and general sibling combinators.
Key Topics
Descendant Combinator
The descendant combinator (a space) selects all elements that are descendants of a specified element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Descendant Combinator</title>
<style>
div p {
color: blue;
}
</style>
</head>
<body>
<div>
<p>This paragraph is inside a div.</p>
</div>
<p>This paragraph is not inside a div.</p>
</body>
</html>
Explanation: Only the paragraph inside the div is selected and styled, as defined by the descendant combinator div p
.
Child Combinator
The child combinator (>
) selects only the direct children of a specified element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Child Combinator</title>
<style>
div > p {
color: green;
}
</style>
</head>
<body>
<div>
<p>This is a direct child.</p>
<span>
<p>This is not a direct child.</p>
</span>
</div>
</body>
</html>
Explanation: Only the paragraph that is a direct child of the div is styled, as defined by the child combinator div > p
.
Adjacent Sibling Combinator
The adjacent sibling combinator (+
) selects an element that is immediately preceded by a specified element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Adjacent Sibling Combinator</title>
<style>
h1 + p {
color: red;
}
</style>
</head>
<body>
<h1>Heading</h1>
<p>This paragraph is immediately after the heading.</p>
<p>This paragraph is not immediately after the heading.</p>
</body>
</html>
Explanation: Only the first paragraph after the <h1>
is selected and styled using h1 + p
.
General Sibling Combinator
The general sibling combinator (~
) selects all elements that are siblings of a specified element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>General Sibling Combinator</title>
<style>
h1 ~ p {
font-style: italic;
}
</style>
</head>
<body>
<h1>Heading</h1>
<p>This paragraph is a sibling of the heading.</p>
<p>This paragraph is also a sibling of the heading.</p>
</body>
</html>
Explanation: All paragraphs that are siblings of the <h1>
are styled using h1 ~ p
.
Key Takeaways
- Descendant: Targets all nested elements.
- Child: Targets only direct children.
- Adjacent Sibling: Targets the immediate sibling.
- General Sibling: Targets all siblings.