Pseudo-classes
Pseudo-classes allow you to style elements based on their state or position:
- :hover: Styles an element when the mouse hovers over it.
- :focus: Styles an element when it gains focus.
- :nth-child(n): Styles elements based on their position in a parent.
- :first-child: Styles the first child of a parent.
- :last-child: Styles the last child of a parent.
Pseudo-elements
Pseudo-elements allow you to style specific parts of an element:
- ::before: Inserts content before an element.
- ::after: Inserts content after an element.
- ::first-letter: Styles the first letter of an element.
- ::first-line: Styles the first line of an element.
Example: Pseudo-classes & Pseudo-elements
/* Example */
a:hover {
color: red;
text-decoration: underline;
}
p::first-line {
font-weight: bold;
color: blue;
}
This example changes the color and style of links on hover and styles the first line of a paragraph.
Practice
Try experimenting with pseudo-classes and pseudo-elements:
- Use
:nth-child()to style specific list items. - Combine
::beforeand::afterfor decorative effects. - Style form elements using
:focus.
Continue Learning
Quick Check
Which pseudo-class styles a link when the mouse pointer is over it?