goodland avatar

Dealing with long words in headers - a recursive approach

goodland

Published: 06 Feb 2018 › Updated: 06 Feb 2018Dealing with long words in headers - a recursive approach

Dealing with long words in headers - a recursive approach

Using long words in headers is usually no problem on websites, but when it comes to mobile views it can become one. I stumbled over this problem in one of my projects:

screen1.png

The shown content comes from a content management system, so hyphens are no solution here. Using word-break does not look good either. So I came up with a little recursive function in javascript to solve this:

function fixHeader(header){       
  if($(header).get()[0].scrollWidth>$(header).parent().width()){
    $(header).css("font-size", (parseInt($(header).css("font-size"))-1)+"px");
    fixHeader(header);
  }
}

This approach uses jQuery, but it's also possible to use javascript only. It reduces the size of the header until it the longest word fits in the container. To use the function just call

fixHeader($('#element_to_fix'));

screen2.png

Feel free to use this code or come up with a nicer solution. If anybody knows a CSS only way to achieve this result I would be glad to here it.

Leave Dealing with long words in headers - a recursive approach to:

Written by

Read more #javascript posts


Best Posts From goodland

We have not curated any of goodland's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From goodland