Pseudo-classes and Pseudo-elements in CSS
CSS (Cascading Style Sheets) is used to style HTML elements to enhance the
appearance of web pages. Two powerful tools in CSS that allow for advanced styling
without additional HTML are pseudo-classes and pseudo-elements. These features help
target elements based on their state or insert content without altering the HTML structure.
Pseudo-classes and pseudo-elements enhance the styling power of CSS without
altering HTML. While pseudo-classes are used to style elements based on user interaction
or document structure, pseudo-elements are used to style specific parts or inject content
into elements. Mastering these tools enables developers to create rich, dynamic, and
interactive user experiences efficiently.
1. Pseudo-class
A pseudo-class is a keyword added to selectors that specifies a special state of the
selected elements. It allows you to style elements not only based on their content or
attributes, but also on user interaction or document structure.
Syntax:
selector:pseudo-class {
property: value;
}
Examples:
1. :hover — Styles an element when the mouse hovers over it.
button:hover {
background-color: green;
color: white;
}
2. :focus — Applies styles when an input field is focused.
input:focus {
border: 2px solid blue;
}
3. :nth-child(n) — Selects the nth child of a parent.
li:nth-child(2) {
color: red;
}
4. :first-child — Targets the first child of a parent.
p:first-child {
font-weight: bold;
}
5. :checked — Styles a selected radio button or checkbox.
input:checked {
box-shadow: 0 0 5px green;
}
2. Pseudo-element
A pseudo-element is used to style specific parts of an element or insert content
before or after it without changing the HTML.
Syntax:
selector::pseudo-element {
property: value;
}
Examples:
1. ::first-line — Styles the first line of a text block.
p::first-line {
font-weight: bold;
color: navy;
}
2. ::first-letter — Styles the first letter of an element.
p::first-letter {
font-size: 200%;
color: red;
}
3. ::before — Inserts content before an element.
h1::before {
content: "★ ";
color: gold;
}
4. ::after — Inserts content after an element.
h1::after {
content: " ✔";
color: green;
}
5. ::selection — Styles the part of the document that is selected by the user.
::selection {
background: yellow;
color: black;
}