CSS Series
15 CSS Selectors You Should Know!
From * to custom data attributes
I’m going to show you the most used CSS selectors, yes! 15 of them! Simply, easy, few words, so, go get them, tiger!!
1) * (Asterisk)
Starting from the most basic, the asterisk! This selector is going to match with all elements in DOM
2) # (ID)
The ID selector, it will match with the ID you assign to an element. Just be carefully ID selector should be not reused.
3). (Class)
The Class selector can be used when you want to style a group of elements.
4) elem1 elem2 (Descendant)
The descendant selector is used when you need to be more specific with your selectors. For example, if you need to select all the OL inside a DIV, how do you do it? This is the right way…
5) elem (Type)
If you need to select all elements by type, this is your salvation, it will get every element with the type you want.
6) elem1 + elem2 (Adjacent)
The adjacent selector. It will select only the elem2 that is immediately preceded by the elem1.
7) elem1 > elem2 (Child)
This selector will just select elem2 that are direct child of elem1.
8) elem1 ~ elem2 (Sibling)
The sibling selector will select all elem2 behind elem1
9) elem[attr] (Attribute)
The attribute selector adds more specificity to the css, so, if you need, for example, select all elem with some specific attribute, this is your salvation.
10) elem[href=’google’] (Attribute)
So, if you have a group of elements with attributes, and you want to select just that element with a full matching attribute, you should use this (and the following six variation)
11) elem[href*=’google’]
Same as 10, but now it's going to match to all those who has ‘google’ inside.
12) elem[href^=’https’]
Same as 10/11, but now it’s going to match to all those who starts with ‘https’.
13) elem[href$=’.com’]
Same as 10/11/12, but now it’s going to match to all those who end with ‘.com’.
14) elem[data-attribute=’foo’]
Custom data attributes will be another way to affect just one or a few from a bigger group of same elements.
15) elem[data-attribute~=’bar’]
Like the previous example, but now if your custom data attribute has more tan a value, you can make it match with just one value.
This is all folks!!
As I always say
Hope this helps!