A Complete Guide to CSS ::before & ::after

The ::before and ::after pseudo-elements in CSS allow us to insert content before or after an element, respectively, without having to modify the HTML code. In this complete guide, we’ll explore how to use these pseudo-elements in different ways.

Syntax

The syntax for creating a ::before or ::after pseudo-element is as follows:

css
selector::before {
/* styles */
}

selector::after {
/* styles */
}

The selector can be any valid CSS selector. The ::before or ::after pseudo-element is then attached to the selected element, allowing us to add content before or after it.

Adding Content

One of the most common use cases for ::before and ::after pseudo-elements is to add content to an element. We can use the content property to add text or an image. Here’s an example:

css
div::before {
content: "Before content";
}

div::after {
content: url("image.png");
}

In this example, we add text before the div element using the content property. We then add an image after the div element using the content property and the url function.

Styling

We can also use ::before and ::after pseudo-elements to style elements. Here’s an example:

css
button::before {
content: "";
display: block;
height: 10px;
width: 10px;
background-color: red;
}

button::after {
content: "";
display: block;
height: 10px;
width: 10px;
background-color: blue;
}

In this example, we add two pseudo-elements to a button element. We set the content property to an empty string, effectively creating a new element. We then set the display property to block and specify the height, width, and background-color properties to style the elements.

Positioning

We can also use ::before and ::after pseudo-elements to position elements relative to their parent element. Here’s an example:

css
div {
position: relative;
}

div::before {
content: "";
display: block;
position: absolute;
top: -10px;
left: 0;
height: 10px;
width: 10px;
background-color: red;
}

In this example, we set the position property of the parent div element to relative. We then position the ::before pseudo-element using the position property set to absolute. We use the top and left properties to position the element relative to the parent div element.

Conclusion

The ::before and ::after pseudo-elements in CSS are powerful tools that allow us to add content, style, and position elements in creative ways. By using these pseudo-elements, we can keep our HTML code clean and flexible, while still achieving our desired design goals.