CSS Pseudo Elements are a powerful tool in web design that allows you to style specific parts of an element. They are denoted by a double colon ::
.
It’s important to note that although you may sometimes come across pseudo-elements with a single colon, using two colons is the recommended syntax to distinguish them from pseudo-classes.
The most commonly used pseudo-elements are ::before
and ::after
, which are used to add content before or after an element, such as icons. Here is a list of the available pseudo-elements:
::after
: creates a pseudo-element after the element::before
: creates a pseudo-element before the element::first-letter
: styles the first letter of a block of text::first-line
: styles the first line of a block of text::selection
: targets the text selected by the user
Let’s dive into an example to illustrate how these pseudo-elements can be used. Suppose you want to make the first line of a paragraph slightly bigger in font size:
p::first-line {
font-size: 2rem;
}
Or perhaps you want the first letter to be bolder:
p::first-letter {
font-weight: bolder;
}
Using ::after
and ::before
may be a bit less intuitive. These pseudo-elements come in handy when you need to add icons using CSS. To insert content before or after an element, use the content
property:
p::before {
content: url(/myimage.png);
}
.myElement::before {
content: "Hey Hey!";
}
With CSS Pseudo Elements, you have the ability to enhance your web design by targeting specific elements and adding visual enhancements. Experiment with these powerful tools to take your website to the next level.