What are pseudo-element selectors in CSS?

Pseudo-element selectors in CSS are a way to style certain parts of an element that are not typically selectable by other CSS selectors. These parts can include the first line or first letter of a text block, generated content before or after an element's content, and even selections of that content. Pseudo-elements are prefixed with double colons (::) to distinguish them from pseudo-classes, which use a single colon (:).

Here are some commonly used pseudo-element selectors:

::before and ::after

These pseudo-elements are used to insert content before or after the content of an element. This content is styled as part of the document tree even though it does not exist in the document HTML source. They are commonly used for decorative effects.

Example in CSS:

.element::before {
  content: "★ ";
  color: gold;
}

.element::after {
  content: " ★";
  color: gold;
}

::first-line

The ::first-line pseudo-element targets the first line of a block-level element. This can be useful for drop caps and styling the opening lines of articles.

Example in CSS:

p::first-line {
  font-weight: bold;
  font-size: 1.2em;
}

::first-letter

The ::first-letter pseudo-element selects the first letter or number in a block of text, which is often used for styling initial letters in a paragraph (drop caps).

Example in CSS:

p::first-letter {
  font-size: 2em;
  float: left;
  margin-right: 4px;
  line-height: 1;
}

::selection

The ::selection pseudo-element applies styles to the portion of a document that has been highlighted by the user (such as clicking and dragging the mouse across text).

Example in CSS:

::selection {
  background: yellow;
  color: black;
}

Compatibility and Usage Notes

  • The double colon (::) syntax was introduced in CSS3 to distinguish pseudo-elements from pseudo-classes. However, for compatibility with older versions of CSS (CSS2), pseudo-elements like ::before, ::after, ::first-line, and ::first-letter can also be used with a single colon (:). For example, :before is equivalent to ::before in browsers that only support CSS2 syntax.
  • Not all pseudo-elements can be used with all types of elements. For example, ::first-line and ::first-letter are typically only supported on block-level elements.
  • Pseudo-elements cannot be used alone. They must be attached to a selector that targets an actual element in the document.
  • The content property is almost always required when using ::before and ::after, as it specifies what is to be inserted.

Pseudo-elements are a powerful feature in CSS, allowing developers to create complex styles without adding unnecessary elements to the HTML document. They enhance the presentation of content while keeping the markup clean and semantic.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon