Dealing with long words in headers - a recursive approach

in javascript •  7 years ago 

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.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!