What is ::before and ::after?

CSS Selector ? CSS Class? CSS Element? Let's find out.

Let's first clear few definitions to understand ::before and ::after better.

Preface :

Element: An HTML tag.

Class: Group of HTML elements.

Selector: Way to select a class or an element of a html page and apply some rules/properties to them.

Definition

So let me spill the beans, ::before and ::after are pseudo elements.

You know what element is according to above definition, so before and after are pseduo element that adds an element*, that is content, before or after a selector.

Too much, breaking it down for you with an example:

Example: Text content

It addes the content i have given in CSS's content property and adds it after the selected class (class selector).

Display Type (Block, In-line)

Here by default pseudo elements have way of display in-line with the selected class element they are in, you can change that by adding a display property of block and the content will be shown as a block element.

.before-class::before{
            content: 'Added Before ';
            background-color: white;
            color:red;
            display:block
        }

I read about content property a little bit more from mdn docs and got to know that we can even show image as a content.

Content As Image

Example:

Also can combine image and text together like this

.before-class::before{
            content: "Work" url(https://images.unsplash.com/photo-1667844670191-7404253623af?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=200&q=80) "hard";

Side Note

*Adding an element means it looks like a tag but its not, when inspecting tag it will only show ::before or ::after whichever is used. Showing image

Insight

highlighted.png

Also they are showing in order like ::before is shown before the actual text that is written and ::after is shown after the actual text.

Did you find this article valuable?

Support Anuj Mistry by becoming a sponsor. Any amount is appreciated!