MyInternships.in

CSS Tutorial

CSS Pseudo-classes

A pseudo-class is a keyword added to a selector that targets an element in a special state or position — when it is hovered, focused, the first of its kind, or every other row. They add interactivity and precision without any extra HTML.


What is a pseudo-class?

A pseudo-class starts with a single colon and describes a condition an element can be in. Some are dynamic and respond to user actions like hovering or focusing, while others are structural and depend on an element's position among its siblings. You attach them directly to a selector, as in button:hover or li:first-child.

Pseudo-classSelects an element that…
:hoverHas the mouse pointer over it
:focusIs focused, such as a clicked input
:first-childIs the first child of its parent
:last-childIs the last child of its parent
:nth-child(n)Matches a position pattern like 2 or even/odd
:checkedIs a ticked checkbox or radio button
:disabledIs a disabled form control

Interactive states: hover and focus

Example
<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: system-ui, sans-serif; padding: 20px; }
  button {
    padding: 10px 18px;
    border: none;
    background: #2563eb;
    color: white;
    border-radius: 6px;
  }
  button:hover { background: #1d4ed8; }
  input:focus  { outline: 3px solid #16a34a; }
</style>
</head>
<body>
  <button>Hover me</button>
  <br><br>
  <input placeholder="Click to focus">
</body>
</html>

Structural: first-child and nth-child

Structural pseudo-classes target elements by their position. :nth-child accepts numbers, the keywords even and odd, or formulas like 3n. This is how zebra-striped lists are made without extra classes.

Example
<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: system-ui, sans-serif; padding: 20px; }
  li { padding: 8px; list-style: none; }
  li:first-child      { font-weight: bold; color: #7c3aed; }
  li:nth-child(even)  { background: #eef2ff; }
</style>
</head>
<body>
  <ul>
    <li>First item (bold, purple)</li>
    <li>Second item (striped)</li>
    <li>Third item</li>
    <li>Fourth item (striped)</li>
  </ul>
</body>
</html>
⚠️

Do not confuse pseudo-classes (single colon, an element state) with pseudo-elements (double colon, a generated part of an element like ::before).

Key points

  • Pseudo-classes use a single colon and target an element's state or position.
  • Dynamic ones like :hover and :focus react to user interaction.
  • Structural ones like :first-child and :nth-child target by position.
  • :nth-child accepts numbers, even/odd, and formulas such as 3n.

Related CSS Topics

Keep learning with these closely related tutorials.

Ready to use your CSS skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships