Combinators are used to define the relationship between the selectors.
There are four different combinators in CSS3:
- descendant selector (space)
- child selector (>)
- adjacent sibling selector (+)
- general sibling selector (~)
Descendant selector (space) : Matches an element that is a descendant of a specified element.
<!DOCTYPE html>
<html>
<head>
<style>
div p {
background-color: red;
}
</style>
</head>
<body>
<div>
<p>Para 1 in the div.</p>
<p>Para 2 in the div.</p>
<span><p>Para 3 in the div.</p></span>
</div>
<p>Para 4 Not in a div.</p>
<p>Para 5 Not in a div.</p>
</body>
</html>
Child selector (>) : Selects an element that is the immediate child of a specified element.
<!DOCTYPE html>
<html>
<head>
<style>
div > p {
background-color: red;
}
</style>
</head>
<body>
<div>
<p>Para 1 in the div.</p>
<p>Para 2 in the div.</p>
<span><p>Para 3 in the div.</p></span> <!-- not Child but Descendant -->
</div>
<p>Para 4 not in a div.</p>
<p>Para 5 not in a div.</p>
</body>
</html>
Adjacent sibling selector (+) : Selects an element that is an adjacent sibling to a specified element.
<!DOCTYPE html>
<html>
<head>
<style>
div + p {
background-color: red;
}
</style>
</head>
<body>
<div>
<p>Para 1 in the div.</p>
<p>Para 2 in the div.</p>
</div>
<p>Para 3 not in a div.</p>
<p>Para 4 not in a div.</p>
</body>
</html>
General sibling selector (~) : Selects an element that’s a sibling to a specific element.
<!DOCTYPE html>
<html>
<head>
<style>
div ~ p {
background-color: red;
}
</style>
</head>
<body>
<div>
<p>Para 1 in the div.</p>
<p>Para 2 in the div.</p>
</div>
<p>Para 3 not in a div.</p>
<p>Para 4 not in a div.</p>
</body>
</html>
0 Comment(s)