DEV Community

Cover image for Head start with CSS Pseudo Elements
Dany Paredes
Dany Paredes

Posted on

Head start with 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.

<main>
    <h1>Pseudo elements</h1>
    <p>I use javascript for some DOM Changes.</p>
    <p>I use Javascript to add some effects.</p>
</main>
Enter fullscreen mode Exit fullscreen mode
  • 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.. "
}
Enter fullscreen mode Exit fullscreen mode

::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.

::first-letter

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

::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.

::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.

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

Top comments (0)