CSS pseudo-classes and pseudo-elements have three main differences in terms of:
Syntax
Pseudo-classes and pseudo-elements have a different syntax:
selector:pseudo-class { }
selector::pseudo-element { }
Pseudo-classes are preceded by a single colon (:) while pseudo-elements are preceded by a double colon (::).
Please note that this syntactical distinction was not present in older versions of the W3C spec. Therefore, most browsers support the use of single colon (:) and double colon (::) for pseudo-elements.
Functionality
Pseudo-classes allow styling based on some special state of the selected element(s) while pseudo-elements allow styling of a specific part of the selected element(s). For example:
<ul>
<li>foo</li>
<li>bar</li>
</ul>
li::selection { background-color: pink; }
li:hover { text-decoration: line-through; }
This does the following:
- The
::selectionpseudo-element applies styles to thelielement that has been highlighted by the user; - The
:hoverpseudo-class matches when the user hovers over thelielement with the cursor (mouse pointer).
Application
There can only be one pseudo-element per selector. However, the same is not true for pseudo-classes as they can be combined to select a specific state of the element. For example:
<label for="foo">Foo</label> <input id="foo" type="text" required />
label[for]::after { content: ': '; }
input:invalid:focus:hover { outline-color: red; }
This does the following:
::aftercreates a pseudo-element as the last child of thelabelelement to add ":" to its content;- The
:invalid:focus:hoverpseudo-class matches when theinputfield is invalid, has focus and the user hovers over the element.
You can also combine pseudo-element and pseudo-classes together. For example:
p:first-of-type::first-line { font-weight: bold; }
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.