CSS Pseudo-elements

Theory & Deep Explanation

Pseudo-elements in CSS are powerful tools that let you style specific parts of an element or insert content before or after it, without extra HTML. They enable advanced effects, custom highlights, and creative UI patterns, all while keeping your markup clean and semantic.

How Pseudo-elements Work

Advanced Use Cases

Accessibility & Best Practices

Code Examples

/* Animated badge with ::after */
.badge::after {
  content: '●';
  color: #e74c3c;
  margin-left: 8px;
  font-size: 1.2em;
  animation: pulse 1.2s infinite alternate;
}

/* Custom list marker */
ul.custom-list li::marker {
  color: #3498db;
  font-size: 1.2em;
}

/* Progress bar using ::before */
.progress-bar {
  position: relative;
  background: #eee;
  border-radius: 8px;
  height: 18px;
  width: 180px;
  margin: 10px 0;
}
.progress-bar::before {
  content: '';
  display: block;
  background: linear-gradient(90deg, #3498db 60%, #8e44ad 100%);
  height: 100%;
  border-radius: 8px 0 0 8px;
  width: 60%;
  transition: width 0.5s;
}

/* Custom placeholder and selection */
input::placeholder {
  color: #8e44ad;
  font-style: italic;
  opacity: 0.8;
}
input:focus::placeholder {
  color: #3498db;
  opacity: 1;
}
input::selection {
  background: #ffd200;
  color: #222;
}

Interactive Demos

Animated badge (::after) Notifications
A pulsing badge is added after the text using ::after.
Custom list marker (::marker)
  • Blue marker
  • Another item
List markers are styled with color and size.
Progress bar (::before)
A progress bar is created using ::before.
::before & ::after
Decorative icons added before and after the button text.
::first-letter & ::first-line

This paragraph demonstrates how you can style the first letter and first line of a block of text using pseudo-elements. Try resizing the box to see the effect.

First letter is large and colored, first line is bold.
::selection

Select some of this text to see a custom highlight color using ::selection.

Try selecting the text above.
::placeholder
Placeholder text is styled with color and italics.
Structural pseudo-classes
  • First item
  • Second item
  • Third item
First, last, nth, only, and empty list items are styled differently.

Try interacting with the demos above to see how pseudo-elements and structural pseudo-classes work in practice.

← Back to Home