CSS3 introduced many new pseudo-classes and pseudo-elements that can be used to style web pages in a more dynamic and sophisticated way. Here are the top 10 differences between CSS3 pseudo-classes and pseudo-elements:
Definition:
A pseudo-class is used to style an element based on its state or relationship to another element,
A pseudo-element is used to style a specific part of an element’s content.
Usage
Pseudo-classes are used to target elements based on their state, such as when they are hovered over or clicked.
Pseudo-elements are used to target specific parts of an element’s content, such as the first letter or line of a paragraph.
Syntax
Pseudo-classes are written with a single colon (:) followed by the name of the class, such as :hover or :active.
Pseudo-elements are written with a double colon (::) followed by the name of the element, such as ::before or ::after.
Examples of CSS3 Pseudo Classes
Below are some examples, but there are many other pseudo-classes that can be used in CSS.
:hover – applies styles when the mouse cursor hovers over an element:
a:hover {
color: red;
text-decoration: underline;
}
:active – applies styles when an element is being clicked:
button:active {
background-color: #333;
color: #fff;
}
:focus – applies styles when an element receives focus, typically through tabbing or clicking:
input:focus {
outline: none;
border: 2px solid blue;
}
:nth-child – selects elements based on their position within their parent element:
ul li:nth-child(odd) {
background-color: #f0f0f0;
}
ul li:nth-child(even) {
background-color: #e0e0e0;
}
:first-child – selects the first child element of its parent:
ul li:first-child {
font-weight: bold;
}
:last-child – selects the last child element of its parent:
ul li:last-child {
border-bottom: 1px solid #ccc;
}
Examples of CSS3 Pseudo Classes
::before – inserts content before the content of an element:
p::before {
content: "Note: ";
font-style: italic;
}
::after – inserts content after the content of an element:
a::after {
content: " (link)";
font-size: 80%;
color: gray;
}
::first-letter – styles the first letter of the text content of an element:
h1::first-letter {
font-size: 200%;
font-weight: bold;
color: blue;
}
::first-line – styles the first line of the text content of an element:
p::first-line {
font-style: italic;
font-weight: bold;
color: #333;
text-transform: uppercase;
}
::selection – styles the portion of text that has been selected by the user:
::selection {
background-color: yellow;
color: black;
}
::placeholder – styles the placeholder text of an input element:
input::placeholder {
color: gray;
font-style: italic;
}
Overall, both pseudo-classes and pseudo-elements are powerful tools for styling web pages in a dynamic and sophisticated way, and their differences reflect their unique strengths and applications.