Pseudo-classes & Pseudo-elements
Pseudo-classes — Element States
Pseudo-classes select elements in a specific state. They use a single colon :.
CSS
/* User interaction */ a:hover { color: #6c63ff; } /* mouse over */ a:visited { color: #9b59b6; } /* clicked before */ a:active { color: #e74c3c; } /* being clicked */ input:focus { outline: 2px solid #6c63ff; } /* focused */ input:disabled { opacity: 0.5; } /* disabled input */ input:checked { accent-color: #6c63ff; } /* checked checkbox */
Structural Pseudo-classes
CSS
li:first-child { color: gold; } /* first item */ li:last-child { color: silver; } /* last item */ li:nth-child(2) { color: red; } /* second item */ li:nth-child(odd) { background: #f5f5f5; } /* 1,3,5... */ li:nth-child(even) { background: #fff; } /* 2,4,6... */ li:nth-child(3n) { font-weight: bold; } /* every 3rd */ p:not(.intro) { font-size: 0.9rem; } /* all p except .intro */ section:empty { display: none; } /* hide empty sections */
Pseudo-elements — Generated Content
Pseudo-elements create virtual elements in the DOM. They use double colon ::.
CSS
/* ::before and ::after — require content property */ .badge::before { content: "★ "; /* content: "" for decorative use */ color: gold; } .price::after { content: " ₹"; /* append currency after price */ } /* Decorative line using ::before */ h2::before { content: ""; display: block; width: 40px; height: 4px; background: #6c63ff; margin-bottom: 0.5rem; }
::first-line & ::first-letter
CSS
p::first-line { font-weight: 600; } p::first-letter { font-size: 3rem; float: left; line-height: 1; margin-right: 0.1em; /* Drop cap effect */ }
::placeholder & ::selection
CSS
input::placeholder { color: #aaa; font-style: italic; } /* Text selection highlight color */ ::selection { background: #6c63ff; color: white; }