CSS3 brought the distinction between pseudo-classes and pseudo-elements with the double-colon (::) syntax to denote the latter. Let's go over what pseudo-classes and pseudo-elements are and what they are used for!
I won't go into EVERY pseudo-class and pseudo-element, which would likely bore you as the reader and me as the writer. Thankfully, someone has already created a complete guide to all of these at the time of writing! You can checkout Ricardo Zea's An Ultimate Guide To CSS Pseudo Classes and Pseudo Elements. And, as always, CSS Tricks and the MDN's pseudo-class and pseudo-element docs are fantastic resources.
What is a pseudo-class?
Pseudo-classes are like an "injected" class into an element. They have the same specificity as regular CSS classes since it behaves like a class. Pretty simple, they just act like CSS classes!
You can use them to add styles in specific states, such as when a navigation item is active (using
:active) or a form element is disabled (
:disabled). You can also add styles to the element depending on where it is in relation to its siblings (
:nth-child(N)) or if the element is (
:is()) or is not (
:not()) a particular element or has a specific class, id, pseudo-class, or attribute selector.
What is a pseudo-element?
A pseudo-element is like a virtual element. It doesn't exist in the DOM, but we can manipulate it as we would regular ole HTML. Since it is like targeting an element, pseudo-elements have the same specificity as an element selector.
Pseudo-elements are great to use when you don't necessarily need or want to add an extra element to the DOM to accomplish a specific task. They can be used to bold the first line or letter (
::first-letter respectively) of a paragraph, or add visual-only information (like with
It's worth noting here that information placed in the
content property may not be accessible to assistive technologies and likely will not get translated into other languages, since that information does not exist in the document tree. We'll discuss this further in a dedicated blog post.
Also since the double-colon (::) selector is new to CSS3, it's not supported by older browsers, namely older versions of Internet Explorer (IE8 and below). You could certainly use the single-colon (:) selector for both pseudo-classes and pseudo-elements for backward compatibility. As always, make sure you're considering where your site or application will be used before making the decision to use newer syntax.
📣 I intend to write a dedicated blog post for the
::after pseudo-elements. Are there any other pseudo-classes or pseudo-elements you'd like to learn more about? Let me know!
Title image from Undraw
Top comments (0)