CSS Combinators
<!DOCTYPE html>
<html>
<head>
<title>CSS Combinators Example</title>
<style>
/* Descendant selector */
div p {
color: red;
}
/* Child selector */
ul > li {
font-weight: bold;
}
/* Adjacent sibling selector */
h1 + p {
text-decoration: underline;
}
/* General sibling selector */
h2 ~ p {
background-color: yellow;
}
</style>
</head>
<body>
<div>
<p>This is a paragraph inside a div.</p>
</div>
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>
<h1>Heading 1</h1>
<p>This paragraph comes after the heading.</p>
<h2>Heading 2</h2>
<p>This paragraph comes after the heading.</p>
<p>This is another paragraph.</p>
</body>
</html>
Code Output
CSS Combinators
CSS combinators are selectors that specify the relationship between elements in a CSS rule.
-
<span>descendant selector (space)</span>
: Targets elements that are descendants of another element.<span>child selector (>)</span>
: Targets elements that are direct children of another element.<span>adjacent sibling selector (+)</span>
: Targets an element that is the immediate next sibling of another element.<span>general sibling selector (~)</span>
: Targets all siblings that come after another element.