Knowing CSS selectors is easily one of the most important aspects of web development. As a former backend developer, it makes me cringe how bad I was at CSS selectors. Not knowing selectors is known to cause mangled front ends and ugly Bootstrap UI’s!
- Element selectors
- Descendant selectors
- Class selectors
- Id Selectors
- Child Selectors
- Adjacent Selectors
- Pseudo Selectors
Element Type Selectors
The most basic CSS selectors are Element Type Selectors. With elements selectors all you are doing is selecting the element.
Element selectors are most common when you first setup your CSS and assign very broad actions like fonts, colors, line heights, etc. Very rarely will you use CSS selectors for things like positioning.
body {
font-family: var(--body-font);
color: var(--text-dark);
}
Descendant Selectors
The descendant selector is used to match elements that are descended from another matched selector.
This selector is easy to spot because it is just a space.
It selects ALL children of the parent regardless of how deeply nested they are.
Descendant selectors can be very broad and many people get them confused with child selectors,
main div {}
body div p {}
Child Selectors
Child selector is very similar to descendant selector but is not as deeply nested and does not target past the immediate selector.
div > p {
font-size: 12px;
color: blue;
}
Also, we can target specific child elements using first-child or last-child selectors.
p:first-child {
color: red;
}
div p:last-child {
color: red;
}
Adjacent Sibling Selectors
div + p {
font-size: 12px;
color: pink;
}
We can use the +
to indicate we want an adjacent sibling element.
When you think of the word adjacent, what comes to mind? Probably something along the lines of right next to something.
The adjacent element only matches the second element if it immediately follows the first element. Also, both selectors must be children of the same parent.
General Sibling Selector (aka tilde selector ~)
This selector is similar to sibling selectors x + y
, but it is not as strict. Adjacent selector (ul + p
) will only selector the first element directly after the former selector, but general sibling selectors all elements.
ul ~ p {
color: red;
}
In this case, sibling selector will select all p
elements following the ul
tag.