Pseudo Selector
In CSS, pseudo-selectors (or pseudo-classes and pseudo-elements) are used to style specific parts of elements or elements in particular states. They help in applying styles dynamically without needing to modify the HTML structure.
Pseudo-Classes (:)
Pseudo-classes target elements based on their state, position, or user interaction.
Pseudo-Class | Description |
---|---|
:hover | Applies styles when the user hovers over an element. |
:focus | Styles an element when it gains focus (e.g., an input field). |
:nth-child(n) | Selects the nth child of a parent element. |
:first-child | Targets the first child of a parent. |
:last-child | Targets the last child of a parent. |
:checked | Styles checkboxes or radio buttons that are checked. |
:disabled | Targets disabled form elements. |
:not(selector) | Excludes elements that match a specific selector. |
Example:
button:hover {
background-color: blue;
color: white;
}
Pseudo-Elements (::)
Pseudo-elements target specific parts of an element.
Pseudo-Element | Description |
::before | Inserts content before an element. |
::after | Inserts content after an element. |
::first-letter | Styles the first letter of a text block. |
::first-line | Styles the first line of a paragraph. |
::selection | Styles text when selected. |
Example:
p::first-letter {
font-size: 2rem;
color: red;
}
p::after {
content: " ✨";
}