Site icon Denis Bouquet

Do a cross browser CSS lettrine for CMS content

HTML lettrine (first letter) are not easy to implement, we play with the font-size and line height. It’s easier to have a tag around the first letter but a bit of a pain to add, especially if the copy come from a CMS. Here how I handle that.

After struggling with the CSS property and the different browser rendering, here is the way I did it at the end

p::first-letter can be a pain (More info at developer.mozilla.org), usually we want it to wrap nicely, not only have a big letter.

So my way consist of a bit of JavaScript (can be a function if you wish) and some CSS to style the letter.

JavaScript:

$('.lettrine').each(function(){
  $(this).find('p').first().html(function (i, html) {
    if (html[1] == " ") {
      // add extra class if the sentence start by a character followed by a space ie: "A long day at..."
      return html.replace(/^[^a-zA-Z]*([a-zA-Z])/g, "< span class="ltrn added-space">$1< /span>");
    }
    else {
      return html.replace(/^[^a-zA-Z]*([a-zA-Z])/g, "< span class="ltrn">$1< /span>");
    }
  });
});

CSS (SASS):

.lettrine {
  .ltrn {
    font-size: 3em;
    float: left;
    position: relative;
    margin-top: 0.1em;
    line-height: 100%;
    display: block;
    &.added-space {
      padding-right: 0.05em;
    }
  }
}

 

Exit mobile version