In this tutorial, we’ll be learning about CSS pseudo-elements!
A pseudo-element is used to style specified parts of an element. For example, we could use it to style the first letter (
::first-letter), or line (
::first-line), of an element. Or we could use it to add content before (
::before), or after (
::after), the content of an element.
You’ll know when you see a pseudo-element, as they start with a double colon
::. Whilst a single colon could also be used, the convention is to use a double to distinguish them from pseudo-classes.
::first-letter is used to style the first letter of a block of text.
::first-line is used to style the first line of a block of text.
::before lets you add content before an element.
::after lets you add content after an element.
::selection targets text selected by the user.
There are more, however they’re considered experimental. In this tutorial, our focus will be on these main pseudo-elements.
As we saw earlier, the
::first-letter pseudo-element is used to add styles to just the first letter of text.
For example, let’s change the first letter of the text in all
<p> elements, to a larger font size:
It should be noted that
::first-letter can only be applied to block-level elements. That is any element that starts on a new line & takes up the full width of the page, such as
<p>, etc. It cannot be applied to inline elements such as
::first-line pseudo-element is used to style the first line of a block of text.
So for example, to give the first line of all
<p> elements a bolder font — we could use the following:
Note that only a subset of the available CSS properties can be used to style a
::first-line. Typically only the font, text & background-related properties.
These are probably the most used pseudo-elements. With
::after, we can insert content onto a page without it needing to be in our HTML. The end result is not actually in the DOM, though it appears on the page as if it is.
A common use case could be to add an icon before the content of each
content property, you can insert any kind of content:
::after pseudo-element can be used to insert some content after the content of an element.
::selection pseudo-element is another extremely useful property. It matches the portion of an element that is selected by a user.
And there we go! We’ve learned all about how to use pseudo-elements to style our content. Pseudo-elements are great! They provide some extremely useful solutions, for when we need to style parts of elements.