简体   繁体   中英

Make text responsive to whether its overflows its parent div

How can I ensure text adjusts its font-size to keep it from overflowing a static, 50px, navbar?

I have a preliminary script, but it doesn't really do the trick. It only adjusts the pixels by 1px for every browser resize, and that doesn't even take into account if someone goes directly to mobile:

          window.onresize = function(){    
            var title = document.getElementById('testing');             
            var style = window.getComputedStyle(title, null).getPropertyValue('font-size');
            var fontSize = parseFloat(style);  
            if(title.scrollHeight > 51){
              title.style.fontSize = (fontSize - 0.5) + 'px';
              $(title).height(50);
            } else if (title.scrollHeight < 51) {
              title.style.fontSize = (fontSize + 0.5) + 'px';
              $(title).height(50);
            }
          };

Just use CSS...

#testing{
    font-size:1.5vw
}

? - Change value accordingly of course

I put together a jQuery solution: http://jsfiddle.net/dsunr5px/1/

It will reduce the size of the text incrementally until it fits within its parent:

jQuery(document).ready(function() {

adjustWidth();

jQuery(window).onresize(adjustWidth());

function adjustWidth() {

    jQuery(".text").each(function() {
        var width = jQuery(this).width();

        while(width <= jQuery(this).children().width() )
        {
            var fontsize = parseInt(jQuery(this).children().css('font-size'));
            var newfs = fontsize - 1 + 'px';
            jQuery(this).children().css({'font-size': newfs}); 
        }
    });
}

});

But, as you can see, it can get a little crazy. A line break would be more user friendly, generally speaking. You might be able to put some more logic in there to determine at what point going too small is too small and it should just do a line break. The industry standard for solving responsive problems, though, is always media queries. Unless you have a driving reason not to, I would investigate a solution in that direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM