DEV Community

Cover image for Intro to pseudo CSS superpowers
mikel brierly
mikel brierly

Posted on

Intro to pseudo CSS superpowers

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 an element.

  • A CSS class is an identifier you give to one or more element.

  • A CSS selector can be used to access HTML elements by their class.

Lloyd sarcastically mouthing "uh yeah" from Dumb and Dumber

Alright fine, let's get into it:

  • A pseudo-class targets the state of an element rather than the element itself. Alt Text Pseudo-classes always (should) follow a CSS selector 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) Alt Text Pseudo-elements always (should) follow a CSS selector and are preceded by two colons ::.

Here's what that would look like in the wild:
Alt Text
Alt Text
☝️ Those are some big honkin gifs, so give 'em a sec

And after those updates, the HTML in the inspector will show this:
Alt Text

::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). 🍻

Top comments (0)