CSS Pseudo-Classes and Pseudo-Elements
Pseudo-Classes
Pseudo-classes define the special state of an element. They are used to apply styles based on the state or the position of an element.
Common Pseudo-Classes:
:hover: Applies when the user hovers over an element.
button:hover { background-color: blue;}:focus: Applies when an element is focused (e.g., an input field)
input:focus { border-color: green;}:nth-child(n): Matches elements based on their position in a parent (1-based index).
li:nth-child(2) { color: red;}:first-child / :last-child: Targets the first or last child element.
p:first-child { font-weight: bold;}:disabled: Targets disabled form elements.
input:disabled { background-color: lightgray;}Pseudo-Elements
Pseudo-elements allow you to style specific parts of an element.
Common Pseudo-Elements:
::before: Inserts content before an element’s actual content.
h1::before { content: "Chapter: "; font-weight: bold;}::after: Inserts content after an element’s actual content.
h1::after { content: " - End"; font-style: italic;}::first-letter: Styles the first letter of a block of text.
p::first-letter { font-size: 2em; color: red;}::first-line: Styles the first line of a block of text.
p::first-line { font-weight: bold;}::selection: Styles the portion of text selected by the user.
::selection { background-color: lightblue;}