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
| Selector | Selects |
|---|---|
a:hover | An element when the mouse is over it |
input:focus | A field that has the cursor |
input:checked | A ticked checkbox or radio |
li:first-child, li:last-child | The 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
| Selector | Selects |
|---|---|
::before, ::after | Adds content before or after an element |
::first-letter | The first letter |
::first-line | The first line |
::selection | The text the visitor selects |
::placeholder | The 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 |
|---|
| No Content Found. |