Font scaling based on width of container

后端 未结 30 2977
面向向阳花
面向向阳花 2020-11-21 04:35

I\'m having a hard time getting my head around font scaling.

I currently have a website with a body font-size of 100%. 100% of what though? This seems t

30条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 05:18

    Artistically, if you need to fit two or more lines of text within the same width regardless of their character count then you have nice options.

    It's best to find a dynamical solution so whatever text is entered we end up with a nice display.

    Let's see how we may approach.

    var els     = document.querySelectorAll(".divtext"),
    refWidth    = els[0].clientWidth,
    refFontSize = parseFloat(window.getComputedStyle(els[0],null)
                                   .getPropertyValue("font-size"));
    
    els.forEach((el,i) => el.style.fontSize = refFontSize * refWidth / els[i].clientWidth + "px")
    #container {
      display: inline-block;
      background-color: black;
      padding: 0.6vw 1.2vw;
    }
    .divtext {
      display: table;
      color: white;
      font-family: impact;
      font-size: 4.5vw;
    }
    THIS IS JUST AN
    EXAMPLE
    TO SHOW YOU WHAT
    YOU WANT

    All we do is to get the width (els[0].clientWidth) and the font size (parseFloat(window.getComputedStyle(els[0],null).getPropertyValue("font-size"))) of the first line as a reference and then just calculate the subsequent lines font size accordingly.

提交回复
热议问题