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
The after
Similar to ::before
, this pseudo-element inserts content after the content of the selected element.
As an example:
Editor
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
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
The selection
This pseudo-element targets the portion of text that has been selected by the user.
As an example:
Editor
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
All CSS Pseudo Elements
Here's a table with all of the CSS pseudo-elements and their syntax:
Pseudo-element | Description | Example |
---|---|---|
::after | Insert content after an element's content | p::after { content: "..." } |
::before | Insert content before an element's content | p::before { content: "..." } |
::first-letter | Select the first letter of an element's content | p::first-letter { font-size: 24px } |
::first-line | Select the first line of an element's content | p::first-line { font-weight: bold } |
::selection | Select the portion of an element's content that is currently selected | ::selection { background-color: blue } |
::placeholder | Select the placeholder text in an input element | input::placeholder { color: gray } |
::marker | Select the marker of a list item | li::marker { color: red } |
::backdrop | Select the backdrop of a dialog element | dialog::backdrop { background-color: rgba(0, 0, 0, 0.5) } |