Pseudo-elements in CSS
CSS pseudo-elements are used to style specific parts of an element's content, such as the first letter, the first line, or the part of the text a user selects. Let's explore the pseudo-elements ::first-letter
, ::first-line
, and ::selection
.
1. Pseudo-element
A pseudo-element allows you to style a specific part of an element’s content. Unlike pseudo-classes, which target entire elements in a specific state, pseudo-elements allow you to style specific portions of the content
2. ::first-letter
The ::first-letter
pseudo-element targets the first letter of the first line of a block-level element, allowing you to apply special styles to it. This is often used for decorative purposes, like in the case of drop caps at the start of a paragraph.
Example: In this example, we have used ::first-letter
pseudo-element to make the first letter of h1 tag to black
h1::first-letter{
color: black;
}
3.::first-line
The ::first-line
pseudo-element targets the first line of a block of text. The length of the first line may change depending on the width of the container or the browser window, but this pseudo-element will apply styles specifically to that first line.
Example:
p::first-line{
color: purple;
}
4. ::selection
The ::selection
pseudo-element applies styles to the part of the text that is highlighted or selected by the user, typically by clicking and dragging over text with a mouse. It allows you to customize the background color, text color, and other properties of the selected text.
Example:
p::selection{
color: red;
}
Summary:
Pseudo-element | Description | Example |
::first-letter | Targets the first letter of a block element for special styling | p::first-letter { font-size: 2em; } |
::first-line | Targets the first line of text within a block element, regardless of how long that line is | p::first-line { font-weight: bold; } |
::selection | Applies styles to the portion of text that is selected or highlighted by the user | ::selection { background-color: yellow; } |