Creating marginal drop caps with jQuery and CSS

Creating marginal drop caps with jQuery and CSS

How to automatically create marginal drop caps with jQuery and style them with CSS.

The book on CSS by Michael Bowers is a milestone in the history of CSS development. In this book Michael presents an interesting technique to create marginal drop caps with CSS. We can improve this technique with jQuery to automatically generate the drop caps on the very first letter of each paragraph.

We have a series of paragraphs. Some of them are marked up with a special CSS class:


<p class="indent">...</p>
<p>...</p>
<p class="indent">...</p>
<p>...</p>

Paragraphs will be left-indented to make room to the drop caps, which will be absolutely positioned to the left:


p {
    margin-bottom: 1em;
    padding-left: 2em;
}

.indent {
    position: relative;
}

.marginal-dropcap {
    font: 2em/0.8 Georgia, serif;
    position: absolute;
    top: 0;
    left: 0;
}
​

With jQuery we only need to select the first letter of each block and replace it with a new HTML element:


var createMarginalDropCaps = function() {
    if ($('p.indent').length) {

        $('p.indent').each(function() {

            var $p = $(this);
            var text = $.trim($p.text());
            var firstLetter = text[0];
            var marginalDropCap = '<span class="marginal-dropcap">' + firstLetter + '</span>';

            $p.html(text.replace(firstLetter, marginalDropCap));

        });

    }
};

createMarginalDropCaps();
​

You can see the demo on this page.