Dany Paredes
Dany Paredes | Javascript / Web

Dany Paredes | Javascript / Web

How to use CSS Pseudo Elements

How to use CSS Pseudo Elements

Dany Paredes's photo
Dany Paredes
·Dec 20, 2020·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

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.

<main>
    <h1>Pseudo elements</h1>
    <p>I use javascript for some DOM Changes.</p>
    <p>I use Javascript to add some effects.</p>
</main>
  • 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!

::before

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 jsfiddle.net/danywalls4/bpjm1vs6/18 result,html,css %}

::after

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 jsfiddle.net/danywalls4/bpjm1vs6/19 result,html,css %}

::first-letter

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

{% jsfiddle jsfiddle.net/danywalls4/bpjm1vs6/20 result,html,css %}

::selection

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 jsfiddle.net/danywalls4/bpjm1vs6/21 result,html,css %}

::first-line

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 jsfiddle.net/danywalls4/bpjm1vs6/30 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

 
Share this