CSS Pseudo-classes and Pseudo-elements

A pseudo-class selects an element in a special state or position (one colon). A pseudo-element selects a part of an element (two colons).


Common pseudo-classes

SelectorSelects
a:hoverAn element when the mouse is over it
input:focusA field that has the cursor
input:checkedA ticked checkbox or radio
li:first-child, li:last-childThe first or last child
li:nth-child(2)The second child
li:nth-child(odd), (even)Odd or even children
p:not(.note)Elements that do not match
.tcx-list li:first-child { font-weight: bold; }
.tcx-list li:nth-child(even) { background: #f2f2f2; }
.tcx-list li:hover { color: red; }
Result of the first rules (the hover colour does not show in this box)
  • First (bold)
  • Second (grey)
  • Third
  • Fourth (grey)


Common pseudo-elements

SelectorSelects
::before, ::afterAdds content before or after an element
::first-letterThe first letter
::first-lineThe first line
::selectionThe text the visitor selects
::placeholderThe placeholder of an input
.price::before { content: "$"; }
.tcx-note::after { content: " (important)"; color: red; }
p::first-letter { font-size: 2em; color: #0073aa; }
What the visitor sees

Price: $49

Read this (important)

Big first letter of this paragraph.

Note: ::before and ::after need the content property, even if it is empty (content: ""). The added text is not part of the HTML, so do not use it for important content.

Summary

  • Pseudo-classes (:) select states and positions.
  • Pseudo-elements (::) select parts of an element or add content.
  • Next: CSS Variables.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is the CSS class selector?
What is grouping in CSS and what is it used for?
What are child selectors in CSS?
What is the difference between id and class selector in CSS?
What is specificity in CSS?
What does !important do in CSS?
What are pseudo-classes and pseudo-elements in CSS?