CSS Pseudo-elements
CSS pseudo-elements allow you to style specific parts of an element. Common pseudo-elements include ::before
, ::after
, and ::first-letter
, which enable precise styling without modifying the HTML structure.
Key Topics
::before and ::after
The ::before
and ::after
pseudo-elements are used to insert content before or after an element’s content, respectively. You can use the content
property to define the inserted content.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Before and After</title>
<style>
p::before {
content: "★ ";
color: gold;
}
p::after {
content: " ✩";
color: gray;
}
</style>
</head>
<body>
<p>This is a paragraph with pseudo-elements.</p>
</body>
</html>
Explanation: The ::before
pseudo-element adds a gold star before the paragraph content, and ::after
adds a gray star after the content.
::first-letter
The ::first-letter
pseudo-element styles the first letter of a block element, such as making it larger or bold.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>First Letter</title>
<style>
p::first-letter {
font-size: 2em;
font-weight: bold;
color: red;
}
</style>
</head>
<body>
<p>This is a paragraph with a styled first letter.</p>
</body>
</html>
Explanation: The first letter of the paragraph is styled to appear larger, bold, and red, creating a visually striking effect.
::first-line
The ::first-line
pseudo-element styles only the first line of a block element, such as changing its font or color.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>First Line</title>
<style>
p::first-line {
font-style: italic;
color: blue;
}
</style>
</head>
<body>
<p>This is a paragraph. Only the first line of this paragraph is styled differently.</p>
</body>
</html>
Explanation: The first line of the paragraph is styled in italics and blue color, emphasizing it visually.
::marker
The ::marker
pseudo-element styles the markers of list items, such as changing the color or font of the bullet or number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Marker</title>
<style>
li::marker {
color: green;
font-size: 1.5em;
}
</style>
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
Explanation: The markers (bullets) for the list items are styled in green and larger font size.
Key Takeaways
- ::before and ::after: Insert content before or after an element’s content.
- ::first-letter: Style the first letter of a block element.
- ::first-line: Style the first line of a block element.
- ::marker: Customize the markers of list items.