Font scaling based on width of container

后端 未结 30 2965
面向向阳花
面向向阳花 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:20

    This may not be super practical, but if you want a font to be a direct function of the parent, without having any JavaScript that listens/loops (interval) to read the size of the div/page, there is a way to do it. Iframes.

    Anything within the iframe will consider the size of the iframe as the size of the viewport. So the trick is to just make an iframe whose width is the maximum width you want your text to be, and whose height is equal to the maximum height * the particular text's aspect ratio.

    Setting aside the limitation that viewport units can't also come along side parent units for text (as in, having the % size behave like everyone else), viewport units do provide a very powerful tool: being able to get the minimum/maximum dimension. You can't do that anywhere else - you can't say...make the height of this div be the width of the parent * something.

    That being said, the trick is to use vmin, and to set the iframe size so that [fraction] * total height is a good font size when the height is the limiting dimension, and [fraction] * total width when the width is the limiting dimension. This is why the height has to be a product of the width and the aspect ratio.

    For my particular example, you have

    .main iframe{
      position: absolute;
      top: 50%;
      left: 50%;
      width: 100%;
      height: calc(3.5 * 100%);
      background: rgba(0, 0, 0, 0);
      border-style: none;
      transform: translate3d(-50%, -50%, 0);
    }
    

    The small annoyance with this method is that you have to manually set the CSS of the iframe. If you attach the whole CSS file, that would take up a lot of bandwidth for many text areas. So, what I do is attach the rule that I want directly from my CSS.

    var rule = document.styleSheets[1].rules[4];
    var iDoc = document.querySelector('iframe').contentDocument;
    iDoc.styleSheets[0].insertRule(rule.cssText);
    

    You can write small function that gets the CSS rule / all CSS rules that would affect the text area.

    I cannot think of another way to do it without having some cycling/listening JavaScript. The real solution would be for browsers to provide a way to scale text as a function of the parent container and to also provide the same vmin/vmax type functionality.

    JSFiddle: https://jsfiddle.net/0jr7rrgm/3/ (click once to lock the red square to the mouse, and click again to release)

    Most of the JavaScript in the fiddle is just my custom click-drag function.

提交回复
热议问题