1. Introduction to Pseudo-Classes
Pseudo-classes are used to define a special state of an element. They allow you to style elements based on their state, position, or relationship with other elements.
Common pseudo-classes include:
- :hover: Styles an element when the user hovers over it.
- :focus: Styles an element when it receives focus.
- :nth-child(): Styles elements based on their position in a parent element.
- :first-child: Styles the first child of a parent element.
- :last-child: Styles the last child of a parent element.
2. Using :hover
The :hover pseudo-class is used to apply styles when the user hovers over an element.
a:hover {
color: #ff0000; /* Change link color on hover */
text-decoration: underline; /* Underline link on hover */
}
3. Using :focus
The :focus pseudo-class is used to apply styles when an element receives focus, such as when a user clicks on an input field.
input:focus {
border-color: #2260e6; /* Change border color on focus */
box-shadow: 0 0 5px #2260e6; /* Add a glow effect on focus */
}
4. Using :nth-child()
The :nth-child() pseudo-class allows you to style elements based on their position in a parent element.
li:nth-child(odd) {
background-color: #f4f4f4; /* Style odd list items */
}
li:nth-child(even) {
background-color: #e0e0e0; /* Style even list items */
}
5. Using :first-child and :last-child
The :first-child and :last-child pseudo-classes allow you to style the first and last child of a parent element, respectively.
li:first-child {
font-weight: bold; /* Style the first list item */
}
li:last-child {
color: #ff0000; /* Style the last list item */
}
6. Introduction to Pseudo-Elements
Pseudo-elements are used to style specific parts of an element. They allow you to insert content before or after an element or style the first letter or line of an element.
Common pseudo-elements include:
- ::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.
7. Using ::before and ::after
The ::before and ::after pseudo-elements allow you to insert content before or after an element.
.quote::before {
content: "“"; /* Insert a quote symbol before the element */
font-size: 2rem;
color: #2260e6;
}
.quote::after {
content: "”"; /* Insert a quote symbol after the element */
font-size: 2rem;
color: #2260e6;
}
8. Using ::first-letter and ::first-line
The ::first-letter and ::first-line pseudo-elements allow you to style the first letter or line of an element.
p::first-letter {
font-size: 2rem; /* Style the first letter */
font-weight: bold;
color: #2260e6;
}
p::first-line {
font-weight: bold; /* Style the first line */
color: #ff0000;
}