dynamically changing the size of font size based on text length using css and html

前端 未结 8 1267

I need to display user entered text into a fixed size div. What i want is for the font size to be automatically adjusted so that the text fills the box as much as possible.<

8条回答
  •  忘掉有多难
    2020-12-08 04:56

    Using very little Javascript, you can assign a CSS class with the length of the string, eg: text-length-5 or text-length-20

    Then use exclusively CSS to target different font-size according to those class names.

    It probably won't work for every case, but it did very well for mine, where the max length was about 10-12 chars.

    If you have 100+ or 1000+ chars you can also make a function that receives the length and returns a CSS class, then style base on those ranges.


    HTML:

    ABC
    ABCDE

    Javascript (jQuery, but the same idea can be applied to React, or vanilla JS)

    $(".box").each((i, el)=> {
      const length = $(el).text().length;
      $(el).addClass("text-length-"+length);
    })
    

    CSS:

    .box {
      font-size: 16px;
    }
    .box.text-length-4,
    .box.text-length-5,
    .box.text-length-6 {
      font-size: 12px;
    }
    

提交回复
热议问题