Grouping Selectors
Say there are two groups of HTML elements which should have the same CSS style declarations added to them, for example the same background-color and text-color.
In order to cut things short, we use grouping selectors to avoid repetitions. Let’s take a simple example with and without grouping: :
.topic1 {
background-color : yellow;
text-align : center;
}
.topic2 {
background-color : yellow;
text-align : center;
}
.topic1,
.topic2 {
background-color : yellow;
text-align : center;
}
Though the both codes above look and function the same, you can clearly see that the later is much cleaner and non-repetitive.
Chaining Selectors
Chaining selectors are usually used to chain multiple HTML elements having common classes and/or IDs.
It simply means that within any HTML element like <h1>,<div> or <p> , it can chain multiple selectors like classes or IDs.
Here’s an example to clear the doubts:
<div>
<div class="main header">Latest News</div>
<p class="main" id="para">This is what happened today in Mumbai</p>
</div>
.main.header {
color: green;
}
.main#para {
color: blue;
}
Here .main.header chaining selector selects the <div> and .main#para selects the <p> elements. Also, there’s no space between the selectors. That’s how chaining selectors should be, without any space.
But now, for example the HTML and CSS file above looks like this:
<div>
<div class="main header">Latest News</div>
<p class="main header">This is what happened today in Mumbai</p>
</div>
.main.header {
color: red;
}
Now, both <div> and <p> elements will be selected and all of the content within will turn red. It can select multiple multiple HTML elements which have been chained. It’s so simple! Try this yourself by copying the codes in your text editor.