CSS Pseudo-elements
CSS pseudo-elements are used to style specified parts of an element. They allow you to style elements in ways that cannot be done with regular CSS selectors.
1. ::before
Pseudo-element
The ::before
pseudo-element can be used to insert content before the content of an element.
Example:
<div class="example">This is a div element.</div>
<style>
.example::before {
content: "Example:";
font-weight: bold;
display: block;
margin-bottom: 10px;
}
</style>
2. ::after
Pseudo-element
The ::after
pseudo-element can be used to insert content after the content of an element.
Example:
<div class="example">This is a div element.</div>
<style>
.example::after {
content: " - End of example";
font-style: italic;
display: block;
margin-top: 10px;
}
</style>
3. ::first-letter
Pseudo-element
The ::first-letter
pseudo-element can be used to style the first letter of an element.
Example:
<p>This is a paragraph.</p>
<style>
p::first-letter {
font-size: 2em;
font-weight: bold;
color: #ff5722;
}
</style>
This is a paragraph.
4. ::first-line
Pseudo-element
The ::first-line
pseudo-element can be used to style the first line of an element.
Example:
<p>This is a long paragraph that will have the first line styled differently from the rest of the paragraph.</p>
<style>
p::first-line {
font-weight: bold;
}
</style>
This is a long paragraph that will have the first line styled differently from the rest of the paragraph.
5. ::selection
Pseudo-element
The ::selection
pseudo-element can be used to style the part of an element that is selected by the user.
Example:
<p class="content">This text can be selected to see the ::selection pseudo-element in action.</p>
<style>
.content::selection {
background-color: #ffccbc;
color: #333;
}
</style>
This text can be selected to see the ::selection pseudo-element in action.
6. ::before
and ::after
with Quotes
The ::before
and ::after
pseudo-elements can be used to insert quotes around text.
Example:
<div class="quote">This is a quote.</div>
<style>
.quote::before {
content: open-quote;
font-size: 2em;
color: #ff5722;
}
.quote::after {
content: close-quote;
font-size: 2em;
color: #ff5722;
}
</style>
Conclusion
CSS pseudo-elements are powerful tools for styling specific parts of an element’s content. By understanding and using these pseudo-elements, you can create more refined and detailed styles for your web pages.