CSS Pseudo-classes

Styling Element States

Pseudo-classes are used to define a special state of an element.

They allow you to style elements based on user interaction or their position in the document.

/* User Action Pseudo-classes */
a:hover { color: red; }
a:active { color: blue; }
a:visited { color: purple; }
input:focus { border-color: green; }

/* Structural Pseudo-classes */
li:first-child { font-weight: bold; }
li:last-child { border: none; }
li:nth-child(odd) { background: #f0f0f0; }
li:nth-child(3n) { color: red; }

/* State Pseudo-classes */
input:disabled { opacity: 0.5; }
input:checked + label { color: green; }

/* Negation */
p:not(.special) { color: gray; }
  • :hover - Mouse over element
  • :focus - Element has focus
  • :active - Element is being clicked
  • :visited - Visited links
  • :first-child - First child element
  • :last-child - Last child element
  • :nth-child(n) - Nth child element
  • :not(selector) - Elements that don't match
  • :disabled/:enabled - Form element states
  • :checked - Checked checkboxes/radios

Try Pseudo-classes

<ul class="demo-list">
  <li>First Item (bold)</li>
  <li>Second Item</li>
  <li>Third Item</li>
  <li>Fourth Item</li>
  <li>Last Item (no border)</li>
</ul>
<button class="hover-btn">Hover Over Me</button>

Note: Pseudo-classes enhance user experience by providing visual feedback for interactions.