Originally posted on my blog
Selectors in CSS are used to pick elements and style them. They can be very powerful following which one we use. In this post, I will lead you through 6 powerful CSS selectors that will really help you write clean CSS on your next project.
1. div >
a
This selector will enable us to select all a
element where the parent element is a div
tag.
<!-- This one will be selected -->
<div>
<a></a>
</div>
<!-- This one will not be selected -->
<p>
<a></a>
</p>
2. div +
a
This one will select every a
tag placed immediately after a div
element. If we have an element between the div
and the a
tag, that element won't be selected.
<main>
<!-- This one will be selected -->
<div></div>
<a></a>
<!-- This one will be not selected -->
<div></div>
<p></p>
<a></a>
</main>
3. div ~
a
This one will select every a
tag preceded by a div
element on the same level. In other words, if the a
tag is not immediately preceded by a div
element, but has a div
tag as a sibling element, that element will be selected.
<main>
<!-- This one will be selected -->
<div></div>
<a></a>
<!-- This one will be selected -->
<div></div>
<p></p>
<a></a>
<section>
<!-- This one will be selected -->
<div></div>
<p></p>
<a></a>
</section>
<footer>
<!-- This one will be not selected -->
<p></p>
<a></a>
</footer>
</main>
4. [attribute^=
value]
e.g: [class^="list-"]
This selector will pick every element that contains a class
attribute and its value begins with list-
<main>
<!-- This one will be selected -->
<div class="list-element"></div>
<!-- This one will be selected -->
<div class="list-container"></div>
<!-- This one will be selected -->
<div class="list-item"></div>
<!-- This one will be not selected -->
<div class="list__footer"></div>
</main>
5. [attribute$=
value]
e.g: [src$=".png"]
This one will select every src
attribute where its value ends with .png
.
<div>
<!-- This one will be selected -->
<img src="image1.png">
<!-- This one will be not selected -->
<img src="image2.jpg">
<!-- This one will be selected -->
<img src="image3.png">
<!-- This one will be not selected -->
<img src="image4.svg">
</div>
6. [attribute*=
value]
e.g: [class*="-list"]
This selector will pick every element whose class
attribute contains -list
. It does not matter if -list
is at the beginning, the middle or at the end of the class's value. The most important is that the value must contain -list
.
<main>
<!-- This one will be selected -->
<div class="main-list-container"></div>
<!-- This one will be selected -->
<div class="primary-list"></div>
<!-- This one will be selected -->
<div class="primary-list-item"></div>
<!-- This one will be not selected -->
<div class="list-footer"></div>
</main>
Conclusion
Sometimes it's really tough to find the needed element to style due to the fact that our CSS file can be overkill very quick. And using this kind of selector can be very useful depending on your use-case.