Pseudo-Elements
A pseudo-element does not exist as a proper element in an HTML document. Instead, they target specific parts of an element, like its first letter or its first line, or extend it by inserting content before/after it.
In CSS3, a pseudo-element is indicated by a double-colon (::) symbol, as ::before
, ::after
, ::first-letter
, ::first-line
, ::selection
. But if you consider backward compatibility, use a single colon as introduced in CSS2.
::before
The ::before
pseudo-element inserts an inline content before the selected element via the content
property. The content is generated from CSS and is not actually there in the source document.
Consider the <p>
element below
<p>the next teardrop falls</p>
We apply the following CSS to append the text "Before"
before the <p>
element
p::before {
content: "Before ";
}
The HTML document in the browser will appear as
::after
The ::after
pseudo-element does the same thing as ::before
, except that it is used to insert the content after the selected element. As an example, here we insert some text after the content of the <p>
element
<p>Day after day, day</p>
inserting the ::after
pseudo-element to it as
p::after {
content: " after day";
}
which results as below in the HTML page
::first-letter
The ::first-letter
pseudo-element selects the first letter/character of text of the selected element. We can create a drop cap out of the first letter of the <p>
element below
<p>The first letter of this line has a bigger font size.</p>
using the style as
p::first-letter {
font-size: 25px;
}
In the browser, it will appear as
::first-line
The ::first-line
pseudo-element selects the first line of text content of the selected element. Here we colour the first line of the paragraph green
<p>This line is coloured green. <br/> This line is not.</p>
setting the style as
p::first-line {
color: green;
}
the output of which in the browser is as
::selection
A CSS rule can be created to style the selected portion of a document, using the ::selection
pseudo-element. In this example, we set the background colour of selected text to aquamarine.
<p>The selected part of this line is highlighted in aquamarine.</p>
p::selection {
background-color: aquamarine;
}
The highlighted text in browser appears as