Pseudo Elements & Classes
Pseudo Confusion #
I've always just kind of lumped CSS's pseudo-classes and pseudo-elements together and thought they were the same thing. I'm not sure it really ever made a difference in how I wrote styles for them, and it likely didn't help that early pseudo-elements were written the same way as pseudo-classes.
I've also seen pseudo-classes referred to as "pseudo-selectors" which muddies the water, since I believe that term encompasses both pseudo-classes and pseudo-elements.
And even now I have a hard time remembering how many colons to put for elements vs selectors.
All of that is to say: it can be hard. 🙂
So what is the difference? #
To be lazy, this MDN article lays it out fairly well, but ultimately the names themselves give good hints as to their difference:
- A pseudo-class indicates state
:closed
or specific areas that could change when content is changed, such as:first-child
or:last-child
. It's also used for selectors like:not()
,:is()
, etc. You'll note that they have a single colon:
prefixed. - A pseudo-element is like adding a whole fake element into the DOM, and you can give it content; the
::before
pseudo-element is likely the most popular one. Pseudo-elements should have two colons prefixed::
. As mentioned above, some of the older ones still work with a single colon... but don't do that.
The Open-UI proposal for the new Select element (such an exciting proposal, by the way) has some good examples of CSS styling that contains both pseudo-classes and pseudo-elements. Look at this beautiful mix:
select option:hover {
background-color: SelectedItem;
color: SelectedItemText;
}
select option::before {
content: "\2713"/ "";
}
select option:not(:checked)::before {
visibility: hidden;
}
- Previous: AbortControllers for Components