When should I use a pseudo-class instead of a pseudo-element?
Quick answer
Use a pseudo-class when a selector should match an element because of its state or position, such as :hover or :first-child. Use a pseudo-element when you want to target a particular part of an element or create generated content, such as ::first-line or ::before. As a quick test: if the element itself qualifies, consider a pseudo-class; if you mean a part or generated content, consider a pseudo-element. [S1]
The question, the details, the next step.
A practical checklist
Write down what should match: an element, a part of it, or generated content.
For an element’s state or position, try a pseudo-class such as
:hoveror:first-child.For a particular part or generated content, try a pseudo-element such as
::first-lineor::before.If generated text conveys information, include that information in the actual page content.
A few more useful answers
Is `:first-child` a pseudo-class or a pseudo-element?
:first-child is a pseudo-class: it selects an element based on its position in the document. [S1]
Can `::before` create visible text?
Yes, ::before can create generated content. [S1] Because that content is not ordinary authored HTML markup, use actual page content for information readers need.
Sources
References used for this guide.
- [S1] Pseudo-classes and pseudo-elements — MDN developer.mozilla.org · Checked
