CSS pseudo-elements

By onjsdev

Dec 10th, 2023

CSS pseudo-elements are keywords that allow you to style specific parts of an element. They are not real elements in the HTML document, but rather extensions of existing elements that can be targeted and styled with CSS rules.

Benefits of using pseudo-elements:

  • Improved control over styling: You can style specific parts of an element without affecting the element itself.
  • Reduced code complexity: You can avoid adding extra markup to your HTML document to achieve certain visual effects.
  • Increased flexibility: You can use pseudo-elements to create various visual effects, such as drop caps, first-line styles, and content after or before an element.

Syntax of pseudo-elements:

Pseudo-elements are added to a selector using a double colon (::). For example, to style the first line of a paragraph, you would use the following selector:

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

**Commonly used pseudo-elements: ** Here are some of the most commonly used pseudo-elements:

::first-line - Styles the first line of an element. ::first-letter - Styles the first letter of an element. ::before - Inserts content before the element. ::after - Inserts content after the element. ::selection - Styles the selected text within an element. ::placeholder - Styles the placeholder text of an input element.

Examples of using pseudo-elements:

  • Creating drop caps:
p::first-letter {
  display: inline-block;
  font-size: 3em;
  font-weight: bold;
  margin-top: 0.5em;
  margin-right: 0.5em;
  • Adding a background image after an element:
p::after {
  content: "";
  background-image: url("/images/background.png");
  background-size: cover;
  width: 100%;
  height: 50px;
  display: block;
  • Styling the selected text:

Styles the portion of text that is selected by the user.

::selection {
  background-color: #ddd;
  color: #000;


These was jsu a few examples, and there are more pseudo-elements available. Pseudo-elements are a powerful tool for enhancing the styling capabilities.

Thank you for reading