mikel brierly
Posted on August 8, 2020
When folks are learning HTML, CSS, and web development in general, the concepts of elements, classes, and selectors are all taught early on, and often grasped quickly. But what about their weird, colon-prefixed cousins that are often avoided and misunderstood?
pseudo classes, pseudo elements, and pseudo selectors. pseudo is my pseuperhero
Let's recap some foundational pieces:
An
element
is an HTML tag. Any valid markup with<brackets>
is anelement
.A CSS
class
is an identifier you give to one or moreelement
.A CSS
selector
can be used to access HTMLelements
by theirclass
.
Alright fine, let's get into it:
- A
pseudo-class
targets the state of anelement
rather than the element itself. Pseudo-classes always (should) follow a CSSselector
and are preceded by a single colon:
.
- A
pseudo-element
is an "invisible" element originating from your CSS that is intended purely for styling purposes. (It does not become part of the DOM) Pseudo-elements always (should) follow a CSS selector and are preceded by two colons::
.
Here's what that would look like in the wild:
☝️ Those are some big honkin gifs, so give 'em a sec
And after those updates, the HTML in the inspector will show this:
::before
and ::after
are unique in the sense that they accept a "content" property. Without this property, the pseudo-element will not be style-able by your CSS. Often you will see content: ""
if the pseudo-element is only needed for styling. This is called generated content.
If you hear the term pseudo-selector
, it is an umbrella term covering both pseudo-element-selectors and pseudo-class-selectors. You can always tell the difference by checking to see how many colons there are. One for pseudo-class, two for pseudo-element.
caveat from MDN:
As a rule, double colons (::) should be used instead of a single colon (:). This distinguishes pseudo-classes from pseudo-elements. However, since this distinction was not present in older versions of the W3C spec, most browsers support both syntaxes for the original pseudo-elements.
Thanks for reading! If you're interested in learning more, MDN has all the goodies (as per usual). 🍻
Posted on August 8, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.