Dear Ms. FEWD,
What is the difference between a pseudo-element and a pseudo-class? Can you give examples of when each should be used, please?
A pseudo-element allows you to style certain pieces of the HTML document that are not wrapped with any HTML tags. For instance, ::before and ::after allows you insert styling or content before or after the copy/content within that element.
Given the following html:
<a class=”menu-link” href=”#”>Menu Link</a>
We can do the following in CSS, using the ::before pseudo-element:
content: “My Awesome”;
Which will render as “My Awesome Menu Link.”
Or, using the ::after pseudo-element:
Which will render as “Menu Link X.”
You can also find and style the first letter or line within an element using ::first-letter or ::first-line.
A pseudo-class, on the other hand, will define a specific state of the HTML element. For instance, the :hover pseudo-class states that when the mouse is hovering over that element, style it this particular way. Other pseudo-classes for a link are :link, :visited, and :active. Form inputs have multiple states that you can find, like :focus, :blur, :checked, :disabled, and :enabled. You can also find and style elements based on their position within a parent element by using pseudo-classes such as :first-child, :last-child, :first-of-type, :last-of-type, :nth-child(n) or :nth-of-type(n).
There is one “gotcha” I should call out, though. You can see in my examples, I’m using the CSS3 method of distinguishing pseudo-elements (double colon) from pseudo-classes (single colon). However, if you are still supporting a browser like IE8, you should use the CSS2 method of one colon for pseudo-elements (e.g., :before), as these older browsers will not support the double colon.
Do you have a front end development question? Email Ms. FEWD or DM her on Twitter: @MsFEWD.
Photo by MobiusDaXter