Skip to main content

CSS Pseudo-elements: Enhance Element Styles Without Extra Markup

CSS Pseudo-elements are special selectors in CSS that allow you to target and style certain parts of an element's content without needing to add additional markup.

In this tutorial, you'll learn about the following CSS Pseudo-elements:

The before

This pseudo-element inserts content before the content of the selected element. It is often used to add decorative or structural elements.

As an example:

Editor

Loading...

The after

Similar to ::before, this pseudo-element inserts content after the content of the selected element.

As an example:

Editor

Loading...

The first-letter

This pseudo-element selects the first letter of the first line of text in the selected element. It is often used to apply special styling to the first letter of a paragraph.

As an example:

Editor

Loading...

The first-line

This pseudo-element selects the first line of text in the selected element. It is often used to apply special styling to the first line of a paragraph.

As an example:

Editor

Loading...

The selection

This pseudo-element targets the portion of text that has been selected by the user.

As an example:

Editor

Loading...

In this example:

  • We have a paragraph with some text. We're using the ::selection pseudo-element to style the text that is selected by the user.
  • The ::selection pseudo-element sets the background color to blue and the text color to white.
  • When the user selects some text in the paragraph, the selected text will have a blue background and white text.

The placeholder

This pseudo-element allows you to style the placeholder text of an input or textarea element.

As an example:

Editor

Loading...

All CSS Pseudo Elements

Here's a table with all of the CSS pseudo-elements and their syntax:

Pseudo-elementDescriptionExample
::afterInsert content after an element's contentp::after { content: "..." }
::beforeInsert content before an element's contentp::before { content: "..." }
::first-letterSelect the first letter of an element's contentp::first-letter { font-size: 24px }
::first-lineSelect the first line of an element's contentp::first-line { font-weight: bold }
::selectionSelect the portion of an element's content that is currently selected::selection { background-color: blue }
::placeholderSelect the placeholder text in an input elementinput::placeholder { color: gray }
::markerSelect the marker of a list itemli::marker { color: red }
::backdropSelect the backdrop of a dialog elementdialog::backdrop { background-color: rgba(0, 0, 0, 0.5) }