CSS Selectors

CSS selectors are very used to apply specific rules to a bunch of elements, either to a set of two or more elements or to a unique element, thus it is very important you know how and where to use them.

It selects elements that don’t have any other elements inside of them.

div:empty selects all empty div elements.

div:empty {
display: flex;
justify-content: flex-end;
}

:not(X) → Negation Pseudo-class

You can use this to select all elements that do not match selector “X”.

div:not(:first-child) selects every div that is not a first child.

:not(.big, .medium) selects all elements that do not have class=”big” or class=”medium”.

:not(.big, .medium) {
position: relative;
left: 30px;
}

A[attribute] → Attribute Selector

It combines the attribute selector with another selector by adding it to the end.

input[disabled] selects all input elements with the disabled attribute.

input[disabled] {
position: absolute;
z-index: -1;
}

[attribute=”value”] → Attribute Value Selector

input[type=”checkbox”] selects all checkbox input elements.

input[type="checkbox"] {
font-size: 16px;
margin-top: 3rem;
}

[attribute^=”value”] → Attribute Starts With Selector

.user[category^=”Eng”] selects elements with class=”user” and either category=”Eng” or category=”Engineer”.

.user[category^="Eng"] {
background: #fff;
font-size: 3em;
}

[attribute$=”value”] → Attribute Ends With Selector

img[src$=”.jpg”] selects all images which end with .jpg.

img[src$=".jpg"] {
display: flex;
align-items: center;
}

[attribute*=”value”] → Attribute Wildcard Selector

img[src*=”/party/”] selects all image elements that show images from the “party” folder.

[class*=”sales”] selects all elements with “sales” in their class, such as class=”DM-sales” or class=”Post-sales”.

img[src*="/party/"] {
display: flex;
align-items: center;
}

Selectors hierarchy

With these CSS selectors, now you can give styles with other different selectors to class or id, but, how do we know which of them has a major hierarchy when we apply styles? Below, you will find the list containing priority ordering from highest to lowest, on the side, I put their calculating CSS specificity.

The pseudo-class:not() adds no specificity by itself, only what’s inside its parentheses.

In the next chart, I show you some examples of the hierarchy of selectors, (some of them have more hierarchy than others), and their value according to their calculating CSS specificity mentioned above.

Wrapping Up

As you can see in the examples, there are many selectors which you can use to give appropriate styles to a bunch of elements without using class or id. Also, we talk about selectors hierarchy which many times overrides our styles and adds undesired styles to our elements, thus, it’s necessary to know which of them has a major hierarchy to can give the appropriate styles.

If you want to practice more with CSS selectors, I recommend that you follow the GitHub course.