As part of this blog, we are going to see how we can style the first letter of a paragraph different from the remaining words or letter.
How to style the first letter in a paragraph
::first letter is a pseudo element which will apply styles just to the first letter of the first line of any block level element.
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
<style>
p::first-letter {
font-size: 40px;
color: orange;
}
</style>
In the above piece of code, paragraph tag is a block level element. To the first letter of the paragraph tag which is "L" font-size 40px and color orange would be applied.
Now let's see how we can make a dropcap effect i.e the same first letter big enough such that it as long as three or so lines, and the remaining content just flows around it. This can be done in two ways.
- Using CSS initial-letter property
- Adding some customization to the first-letter by adding float, adjusting the line-height and font-size of the letter.
1. CSS initial-letter
- Using css initial-letter property - you can produce a drop cap effect i.e make the letter occupy specified number of lines in a paragraph.
- This accepts only a positive integer. Eg: In the below snippet, letter "L" will span/sink four lines.
- Note - This is only supported by safari at the moment.
p::first-letter {
-webkit-initial-letter: 4;
initial-letter: 4;
font-size: 40px;
color: orange;
}
2. Customize the font of the first-letter
p::first-letter {
float: left;
font-size: 75px;
line-height: 60px;
padding: 3px;
color: orange;
}
In the above piece of code, to the first letter of the paragraph increase the font-size, line-height and float it in such a way that it spans to the number of lines you required. And by adding padding you can adjust the spacing of the first-letter as well.
Are you more of a Twitter person?. Then you can read the same thing in the below thread
Conclusion
Now you should know how to
- Add styles to just the first letter of a paragraph
- Add a drop cap effect to the first letter using CSS initial property or by customizing the fonts of the first letter.
For browser compatability , check canisuse.com
References
Follow me on Twitter | LinkedIn for more web development related tips and posts.
Top comments (4)
Really cool!
Thanks!
Glad you liked it. CSS is always fun.
I did some tests, and it seems "initial-letter" is only supported on Safari (caniuse.com/?search=initial-letter)
But the trick can work anywhere else with "float:left;" instead.
Yes correct. I have added a note in the blog post as well that this is supported only by safari at the moment. And yes float: left does the trick for other browsers. May be I can try creating another example using float: left as a future post.