简体   繁体   中英

constant distance to baseline while dynamically changing font-size - html - text element

As the title says, I try to fix a text element to the baseline while dynamically changing its font-size on window resize .

I made a jsfiddle to illustrate. The problem is, when resizing the window, the distance to the bottom of the window is not constant.

<div class="foo">text</div>

<script>
  var onResizeFunction = function() {
    var newFontSize = Math.floor(0.2 * $(window).width());
    $(".foo").css("font-size", newFontSize);
  };

  onResizeFunction();

  $(window).resize(function() {
    onResizeFunction();
  });
</script>

I tried to fix it like that.

.foo {
  position:fixed;
  bottom: 0;
}

Obviously the problem is the "hitbox" of the text element. Anyway, maybe somebody knows a nice css trick or workaround?

Its running in angular, so no fancy jquery allowed;)

EDIT:

Its about the distance from the bottom of the text element to the bottom of the window. This need to be constant.

The problem here is your line-height in combination with the font you use. As you notice you set the bottom to 0, yet the text is not aligned with the bottom of the window, as you would expect.

This can be solved by setting the line height to a value without a unit. This way the line height will be relative to the font size. One would expect that setting the line height to one would solve this, but this depends on the font, and how much of it's available height it uses.

If you experiment a little you should be able to find the sweet spot though. It won't be 100% accurate, but pretty close. I updated your fiddle as follows, and as you can see with the help of the ruler I added it comes pretty close:

.foo {
    position:fixed;
    font-family: arial;
    bottom: 10px;
    line-height: .7; /* this will depend on the used font */
}

https://jsfiddle.net/u6bd9qfp/2/

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