🎨

Pseudo-elements and Pseudo-classes

Advanced
110 XP
35 min
Lesson Content

Pseudo-elements and Pseudo-classes

Pseudo-classes and pseudo-elements are powerful CSS features that let you style specific parts of elements or elements in specific states.

Pseudo-classes

Pseudo-classes target elements in a specific state:

/* Link states */
a:link { color: blue; }      /* Unvisited link */
a:visited { color: purple; }  /* Visited link */
a:hover { color: red; }      /* Mouse over */
a:active { color: orange; }   /* Being clicked */

/* Form states */
input:focus { border: 2px solid blue; }
input:disabled { opacity: 0.5; }
input:checked { background: green; }

/* Structural */
p:first-child { font-weight: bold; }
p:last-child { margin-bottom: 0; }
p:nth-child(2) { color: red; }
p:nth-child(even) { background: #f3f4f6; }
p:not(.special) { color: gray; }

Pseudo-elements

Pseudo-elements style specific parts of an element (use ::):

/* ::before and ::after - Add content */
.element::before {
  content: "→ ";
  color: blue;
}

.element::after {
  content: " ←";
  color: red;
}

/* ::first-line - Style first line */
p::first-line {
  font-weight: bold;
  color: blue;
}

/* ::first-letter - Style first letter */
p::first-letter {
  font-size: 2em;
  color: red;
}

/* ::selection - Style selected text */
::selection {
  background: yellow;
  color: black;
}

Common Pseudo-classes

  • :hover - When mouse is over element
  • :focus - When element has focus
  • :active - When element is being activated
  • :first-child - First child element
  • :last-child - Last child element
  • :nth-child(n) - Nth child element
  • :not(selector) - Elements that don't match selector

Common Pseudo-elements

  • ::before - Insert content before element
  • ::after - Insert content after element
  • ::first-line - First line of text
  • ::first-letter - First letter of text
  • ::selection - Selected text

Important Notes

  • Pseudo-classes use : (single colon)
  • Pseudo-elements use :: (double colon) in CSS3
  • ::before and ::after require content property
  • Pseudo-elements are inline by default
Example Code

Create styled buttons with hover effects and add decorative elements using pseudo-elements.

<!DOCTYPE html>
<html>
<head>
<style>
.button {
  background-color: #3b82f6;
  color: white;
  padding: 12px 24px;
  border: none;
  border-radius: 5px;
  /* Add hover effect: darker blue background */
  /* Add ::before pseudo-element with "→ " content */
}

/* Add ::before styling */
/* Add :hover styling */
</style>
</head>
<body>
  <button class="button">Click Me</button>
</body>
</html>

Expected Output:

Button with hover and pseudo-element
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code