Home > Mobile >  How to limit CSS Drop Caps to only Filled Paragraphs of more than one line?
How to limit CSS Drop Caps to only Filled Paragraphs of more than one line?

Time:06-28

Given a standard well working Drop Caps styler in pure CSS.

    /* Automatic CSS Drop Caps on First Letter on the First Paragraph */

    article:first-of-type p:first-of-type:first-letter{
      font-size: 3em;
      margin: 0 0 0 0;
      padding: 0 0 0 0;
      line-height: 1em;
      float: left;
    }

Althouth most pages have a big chunky first paragraph, some pages start with just one line of text as their first paragraph. The automatic drop cap makes an odd looking first line with a huge first letter followed by just a couple of words behind it.

enter image description here

Is there a way to narrow down the automatic drop caps to only paragraphs with more than one line or say a minimum of 20 words?

CodePudding user response:

We need to find out whether the paragraph is more than one line. This snippet uses a slightly hacky method of writing a single line (one character) into the innerHTML and measuring its height.

If the actual paragraph is higher than that then a class of DropCap is set. Otherwise a class of oneLineDropCapAlternative is set.

article:first-of-type p.DropCap:first-of-type:first-letter {
  font-size: 3em;
  margin: 0 0 0 0;
  padding: 0 0 0 0;
  line-height: 1em;
  float: left;
}
<div>
  <h2>An article with a long first paragraph</h2>
  <article>
    <p>Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
      Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello </p>
  </article>
</div>
<div>
  <h2>An article with a short first paragraph</h2>
  <article>
    <p>Hello</p>
  </article>
</div>
<div>
  <h2>An article with a first paragraph that is long on narrower viewports</h2>
  <article>
    <p>Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello</p>
  </article>
</div>
<script>
  function init() {
    const ps = document.querySelectorAll('article:first-of-type p:first-of-type');
    ps.forEach(p => {
      const h = window.getComputedStyle(p).height;
      const savedInnerHTML = p.innerHTML;
      p.innerHTML = 'g';
      const tempH = window.getComputedStyle(p).height;
      if (h.replace('px', '') >= (1.1 * tempH.replace('px', ''))) {
        p.classList.remove('oneLineDropCapAlternative');
        p.classList.add('DropCap');

      } else {
        p.classList.remove('DropCap');
        p.classList.add('oneLineDropCapAlternative');
      }
      p.innerHTML = savedInnerHTML
    });
  }
  window.onload = init;
  window.onresize = init;
</script>

  • Related