No history yet

Understanding Pseudo-Elements

Styling Without the Clutter

Imagine you want to add a small decorative icon before every list item on your page, or a special marker at the end of every link. You could go into your HTML and add an extra <span> or <img> tag for each one. But that clutters your markup and makes it harder to maintain.

CSS offers a cleaner way to handle this: pseudo-elements. These are keywords you can add to a selector to style a specific part of an element. They act like extra elements that you can style, but they don't actually exist in your HTML code. This keeps your HTML clean and focused on structure, while CSS handles the presentation.

Meet Before and After

Two of the most common pseudo-elements are ::before and ::after. As their names suggest, they let you insert content just before or just after the content of an element.

::before creates a pseudo-element that becomes the very first child of the selected element. ::after creates one that becomes the last child. You'll notice they use a double colon (::). This is the standard syntax to distinguish pseudo-elements from pseudo-classes (like :hover), which use a single colon.

Pseudo-elements (::before) style a part of an element. Pseudo-classes (:hover) style an element based on its state.

Let's see how they work. To make a pseudo-element appear, you must include the content property in your CSS rule, even if it's empty (content: '';). This property is what actually generates the pseudo-element.

Here's an example. We have a simple list item in our HTML:

<ul>
  <li class="task">Finish report</li>
</ul>

Now, let's use ::before to add a decorative arrow before the text without touching the HTML.

.task::before {
  content: '→ ';
  color: #2a9d8f;
}

This CSS rule selects the .task element and inserts a right arrow () with a teal color before its actual text content. The pseudo-element is treated as an inline element by default, flowing right alongside the text.

Similarly, we can use ::after to add something to the end. Let's add a checkmark to indicate a completed task.

.task::after {
  content: ' ✓';
  color: #e76f51;
  font-weight: bold;
}

This adds a bold, orange checkmark after "Finish report". Both the arrow and the checkmark are added purely with CSS, keeping our HTML simple and clean.

Quiz Questions 1/4

What is the primary purpose of CSS pseudo-elements like ::before and ::after?

Quiz Questions 2/4

Which CSS property is absolutely required for a ::before or ::after pseudo-element to be rendered on the page?