How to use CSS Pseudo Elements

How to use CSS Pseudo Elements

Sometimes style a specific part of an HTML element like the first letter of h1 or append at begin or after, style the first line, my default solution is use JavaScript but not is the best approach if CSS provide a way to solve with Pseudo elements.

The pseudo elements help us style a specific part of HTML element, you can read all about it in MDN or just continue reading.

Using pseudo elements

The pseudo elements start with :: if you are using vscode it shows all pseudo elements, I will implement some of them in.

    <h1>Pseudo elements</h1>
    <p>I use javascript for some DOM Changes.</p>
    <p>I use Javascript to add some effects.</p>
  • Add some text at begin of paragraph using ::before
  • Add ... at end of paragraph ::after
  • Change the color and size for the first letter using ::first-letter
  • Change the color of selection text and letter color using ::selection
  • Take first line and add some style. Let'ts go!


The ::before helps to do some change at the beginning of some selector, for example selector p::before we can add some text using content property.

p::before {
    content: "At begin.. "

{% jsfiddle result,html,css %}


The ::after is a bit similar to ::before, it helps to do some change at the end of some selector. For example the p::after selector add extra dots using content property.

{% jsfiddle result,html,css %}


The ::first-letter takes the first letter of the selector.

{% jsfiddle result,html,css %}


The ::selectionhelps to change the style of the selection of text, for example we change the color of the selected text and also the selection background.

{% jsfiddle result,html,css %}


The pseudo elements can be mixed with pseudo class, using pseudo class we skip first p and the first line change the color and size.

{% jsfiddle result,html,css %}

That's it!

Hopefully, that will give you a bit of help css and pseudo elements.

If you enjoyed this post, share it!

Photo by Pooja Chaudhary on Unsplash