::before / ::after pseudo-element

::before / ::after pseudo-element
Remacle Jean-Claude
1 minute
2021-06-04
css
selector
pseudo-element

These pseudo-elements allows you to insert extra content inside the targeted element without that it's visible in the DOM.

Which do I need to use?

Basically you choose the one above the other on the reason where you want to have your extra content.

  • ::before places the content before the content of that element
  • ::after places the content after the content of that element
div::before {
content: "before";
}
div::after {
content: "after";
}

Above example will generates following code

<div>
before
<!-- all the rest of the content of this element -->
after
</div>

Different types of content

  • empty (content: "";)
    This one is very useful for clearfix
  • string (content: "the string you want to show";)
    If you want to insert special charactersn than it need to be encoded as a unicode entity.
  • image (content: url(/path/to/image.jpg);)
    These images cannot be resized! They will be inserted with the image origal dimensions.
  • counter (content: counter(li);)
    Useful for styling lists, but you can also use ::marker for that