CSS Combinators
In this blog I will try to explain my understanding of CSS Combinators
Why use Combinators?
A CSS selector can contain more than one simple selectors. Combinators are used to explain the relation between multiple selectors. It allows us to use different combinations of selectors to apply style to elements instead giving each of them separate ID.
There are four types of Selectors
Descendant Selector ( )
Child Selector (>)
Sibling Selector (~)
Adjacent sibling Selector (+)
Descendant Selector ( )
The Descendant Selector selects all the elements that are descendant (not only child) of the specified parent element.
For example:
<style>
span p{
color: greenyellow;
background-color: grey;
}
</style>
</head>
<body>
<span>
<p>This is Paragraph 1</p>
<span>
<div><p>This is Paragraph 2</p></div>
<p>This is Paragraph 3</p>
</span>
<p>This is Paragraph 4</p>
</span>
</body>
span p{color: greenyellow;}
applies green color to all the <p>
tags that are descendant of parent <span>
Child Selector (>)
The child Selector (>) selects only those elements that are the child of the specified parent element.
For example:
<style>
div > span{
color: greenyellow;
background-color: grey;
}
</style>
</head>
<body>
<div>
<span>This is span 1</span>
<p><span>This is nested span 2</span></p>
<span>This is span 3</span>
</div>
</body>
div > span{color: greenyellow;}
applies background color to span 1 and span 3 but ignores the 2nd <span>
because it is nested inside <p>
therefore it isn’t a direct child of <div>
Sibling Selector (~)
The sibling Selector (~) selects all the elements that are next siblings to a specified selector.
For example:
<style>
div ~ p{
background-color: greenyellow;
color: rgb(64, 63, 63);
}
</style>
</head>
<body>
<p>Paragraph 1</p>
<div>
<p>Paragraph 2</p>
</div>
<p>Paragraph 3</p>
<span>A span</span>
<p>Paragraph 4</p>
</body>
div~p {background-color: greenyellow;}
applies greenyellow background to all the <p>
that comes after <div>
notice how it didn’t apply to paragraph 1 because it was before the <div>
, and paragraph 2 because it was inside the <div>
Adjacent sibling Selector (+)
The adjacent sibling Selector (+) selects the sibling element only if it immediately after the first mentioned element (immediate/ adjacent sibling), and both are children of the same parent element.
For example:
</style>
<style>
div + p{
background-color: greenyellow;
color: rgb(64, 63, 63);
}
</style>
</head>
<body>
<main>
<div><p>this is a paragraph</p></div>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<span>This is a span</span>
<p>Paragraph 3</p>
</main>
</body>
div + p {background-color: greenyellow;}
only applies to Paragraph 1 as it is the <p>
element that is adjacent to the <div>
element, both of which are have the same parent element <main>
Thanks for reading this blog.
suggestions and feedbacks are greatly appreciated :)