How can I reduce font size based on length?

后端 未结 2 2035
迷失自我
迷失自我 2021-01-18 07:55

Currently I have some large text on a page, and layout works fine for short text (~12-14 chars in length), but any more than that will overflow or wrap. This is undesirable,

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-18 08:23

    You could try an iterative approach using javascript.

    Put the contents into a span with white-space: nowrap. If span is the span within, you can do something like this:

    var maxWidth = span.parentNode.clientWidth;
    var currentFont = parseInt(window.getComputedStyle(span).fontSize); // or max font size
    while(span.offsetWidth > maxWidth) {
        currentFont--;
        span.style.fontSize = currentFont + "px";
    }
    

    This will continually decrement the font until the span fits within its parent.

    If the allocated width changes as you resize the window, you may need to run this on window resize.

提交回复
热议问题