What is a pseudo-element?
sobes.tech AI
Answer from AI
A pseudo-element in CSS is a keyword added to a selector that allows styling a specific part of an element without explicitly creating additional DOM elements.
The most commonly used pseudo-elements:
::before: Inserts generated content before the content of the selected element.::after: Inserts generated content after the content of the selected element.::first-line: Applies styles to the first line of a block-level element.::first-letter: Applies styles to the first letter of a block-level element.::selection: Applies styles to the part of an element selected by the user (e.g., when highlighting text with the mouse).::placeholder: Applies styles to the placeholder text in<input>or<textarea>fields.
Example of using ::before and ::after:
div::before {
content: "Prefix: "; // Required content property
color: blue;
}
div::after {
content: " Suffix"; // Required content property
color: red;
}
Example of using ::first-line and ::first-letter:
p::first-line {
font-weight: bold;
}
p::first-letter {
font-size: 2em;
float: left;
margin-right: 0.1em;
}
Pseudo-elements are useful for adding decorative elements, generating content, styling parts of text, and other tasks, simplifying HTML structure. Historically, they started with a single colon (:), but the CSS3 specification introduced double colons (::) to distinguish pseudo-classes (:hover, :focus) from pseudo-elements, although a single colon is still supported by most browsers for compatibility with older pseudo-elements. It is recommended to use ::.