Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Styling First-Letters with CSS ::first-letter
The CSS ::first-letter pseudo-element allows you to style the first letter of a block-level element. This is commonly used to create decorative drop caps in articles and enhance typography. Note that punctuation marks and special characters can affect which character is considered the "first letter".
Syntax
selector::first-letter {
property: value;
}
Example 1: Styling All First Letters
The following example applies styling to the first letter of all block elements −
<!DOCTYPE html>
<html>
<head>
<style>
body {
text-align: center;
font-family: Arial, sans-serif;
padding: 20px;
}
::first-letter {
font-size: 3em;
color: sienna;
box-shadow: -10px 0 10px green;
background-color: gainsboro;
padding: 5px;
margin-right: 3px;
}
</style>
</head>
<body>
<h2>Beautiful Typography</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Integer eleifend lectus sit amet purus semper, ut pharetra metus gravida.</p>
</body>
</html>
The output of the above code is −
A webpage displaying headings and paragraphs where the first letter of each element appears as a large, sienna-colored character with a gray background and green shadow effect.
Example 2: Targeting Specific Elements
You can target specific elements by combining the element selector with ::first-letter −
<!DOCTYPE html>
<html>
<head>
<style>
body {
text-align: center;
font-family: Georgia, serif;
padding: 20px;
line-height: 1.6;
}
p::first-letter {
font-size: 2.5em;
color: darkviolet;
background-color: silver;
padding: 8px;
margin-right: 5px;
border-radius: 5px;
float: left;
}
</style>
</head>
<body>
<h2>Article Title</h2>
<p>This paragraph has a styled first letter that creates a drop cap effect.</p>
<p>Another paragraph with the same first-letter styling applied.</p>
</body>
</html>
The output of the above code is −
A webpage showing an article title and two paragraphs where only the first letter of each paragraph appears as a large, dark violet character with a silver background, creating a drop cap effect.
Key Points
- Only works on block-level elements like
<p>,<div>,<h1>-<h6> - Limited CSS properties can be applied: font, color, background, margin, padding, border, text-decoration, and text-transform
- Punctuation and quotes before the first letter are included in the selection
Conclusion
The ::first-letter pseudo-element is perfect for creating elegant drop caps and enhancing text presentation. Use it selectively to avoid overwhelming your design with too many decorative elements.
