Have you always used trial and error to style elements when it involves either a colon :
or a pair of colon ::
? Yeah, me too. But today is the day you become confident with your CSS pseudo-selectionโฆwhatever that means lol ;)
In this article, I explain them both with examples and share a few tips for styling elements using either.
The Difference
:
precedes and identifies the state of an element while ::
โcreatesโ element(s). The difference between :
and ::
is that the former describes the state of a selected element usually involving user interaction while the latter is used to create element(s) as a part of the selected element and/or used to target elements using the selected element as reference.
It is important to note that :
creates pseudo-classes, some examples are
:hover
- to style an element when user is on it without selecting ie hovers over an element
:active
- to style an element when clicked ie when element is active
:visited
- to style anchor tags (links) when a user has clicked on it.
:focus
- to style an input field that user clicked on.
While ::
creates pseudo-elements. Some examples of pseudo-elements are
::before
- targets created element that precedes selected element
::after
- targets created element that succeeds selected element
::placeholder
- targets placeholder atrribute value
How to Use
A good rule of thumb is to only use ::
when it is necessary as this got introduced with CSS3 meaning :before
is valid CSS and compatible with older browsers that havenโt fully adopted the changes introduced by CSS3. Following this rule makes your CSS backward-compatible.
It is also good practice to only use CSS-generated content when necessary as CSS-generated elements do not appear on the DOM and therefore cannot be parsed by accessibility tools.
I hope you found this helpful, thank for reading!
Top comments (10)
Thanks, quick but informative ๐๐ป๐๐ป๐๐ป
Thank you!
Awesome! Thanks for sharing.
Thank you!
Great Explanation. Thanks.
Thank you!
Thanks, very interesting this explication. I didn't knew the difference and now is clear in my mind :D
Thanks for reading!
yes but not in practice, same as the & for nesting rules
Thanks for the feedback!