Drop caps (larger first letters of paragraphs which go about multiple lines) are a relatively rare used element in web design, but they can look really great. In this post, I show you how to implement them.
In a project, I had to create drop caps and wrote a quick solution in CSS. This worked for some browsers, for some it did not. Looking for an easy solution, I stumbled upon Adobe’s dropcap.js. The script uses pixel values, which is not really cool in responsive design. If a user resizes its viewport while visiting a web page, the font size will probably change. But the drop cap will not.
To resolve this, I first tried the following: I copied the script’s generated values into my stylesheet and converted them to relative units. Works well, but recently I came across an issue with this solution. What happens, if the user uses another font or the font for which the values were generated cannot be loaded? The answer is easy: the values will not be correct anymore.
With this in mind, it had to be a JavaScript solution. For that, I modified Adobe’s script a bit, so it produces relative values. You can find the result in my Gist.
To use the script, you only have to wrap the first letter from one or more paragraphs inside an element with the class dropcap. The following code shows how to run the script:
<script src='./dropcap.js'></script>
<script>
var dropcaps = document.querySelectorAll(".dropcap");
window.Dropcap.layout(dropcaps, 3);
</script>
Code language: HTML, XML (xml)
The second parameter of window.Dropcap.layout()
specifies the drop cap’s height (number of lines). An optional third parameter specifies the line on which the drop cap stands. The default value for that is the same as the second parameter.
The font size for the paragraphs with drop caps has to be specified through the html
selector. Otherwise, the script will not work probably.