CSS selectors define the elements which pertain to a set of CSS rules. Mostly, we used to use space between the parent class and child class to write the styles for the child class. And now, we can use a class multiple times in a div or an overall page. Even if a class is repeated, we can write styles for the particular class by using the parent class. But, sometimes the parent class may also be the same. In this case, we can use some selectors such as.,
Signs (>, + and ~)
Now you can understand the difference and learn how to use the signs in CSS selectors.
To understand the signs, let us take a small sample code.
First paragraph
second paragraph
Third paragraph
Fourth paragraph
Fifth paragraph
And, this is the style for the
tag.
.container p { font-weight: bold; font-size: 14px; }
This means that the CSS styles (properties) that are applicable for all the
tags are within the container, as it is the descendant selector.
Sign >
We can write the CSS like this:
.container > p { font-weight: bold; font-size: 14px; }
The style is applicable only for the DIRECT child of the container. Here, the direct child is
First Paragraph
,
Fourth paragraph
and
Fifth paragraph
. It will not consider the second and third paragraphs.
Sign +
.container + p { font-weight: bold; font-size: 14px; }
This style is applicable for the IMMEDIATE after the first for the direct element, which is
Fourth paragraph
Sign ~
It is a general sibling combinator and is similar to the + sign. But it is NOT just for the immediate one, it will select all the elements after that.
.container ~ p { font-weight: bold; font-size: 14px; }
This code will target both
Fourth paragraph
and
Fifth paragraph
.
Here is a live example:
The .toolbar class has a set of child classes. Please check with the first screenshot, there is no main parent class or a different class name for the child classes. So if you write a style for a child class, it will target both .toolbar parent class and child classes. To avoid this problem, we can use >, + and ~ signs.
We hope that you’ve now got an idea of using different signs in CSS Selector. If you found this blog helpful, then please do let us know if you have any queries.