简体   繁体   中英

Set font size according to container Width and Height

I'm trying to write a script so that font-size can be set according to container's width, height and the length of the text.

That's what I've done so far.

    window.onload = function () {
    var defaultDimensions = 300;
    var boxWidth = window.innerWidth / Math.floor(window.innerWidth / defaultDimensions);
    var boxes = document.getElementsByClassName('feed');
    for (var i = 0; i < boxes.length; i++) {
        boxes[i].style.width = boxWidth + 'px';
        boxes[i].style.height = boxWidth + 'px';
    }
};
var getFontSizeStatus = function (text) {
    var chars = 250; // Maximum Characters
    var height = 300; // Default Height
    if (text.length < chars) {
        chars = text.length;
    }
    if ((window.innerWidth / Math.floor(window.innerWidth / height)) < height) {
        height = window.innerWidth / Math.floor(window.innerWidth / height);
    }
    height = (height / 10) * 8; // .feed-text height is 80% of .feed's height

    var size = height / chars;
    return size + 'em';
}

Here is the complete code, fiddle.

Current code is working but font-size to container's height, width and text's lengths ratio needs to be fixed.

I would try using a jQuery plugin like fitText

http://fittextjs.com/

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