首页 > 解决方案 > 根据 flexbox 容器的高度设置字体大小

问题描述

我想知道是否可以使用弹性框项目的高度来设置字体大小。我有一个使用视口单位设置的 flexbox 容器,项目的高度由 flex-grow 属性确定。我正在寻找的是将字体大小设置为这些项目的高度,并在视口更改时保留这些关系。

我有一个基本的想法,但我不完全确定如何仅隔离字母(基线到大写高度)并将其缩放到项目容器。

https://codepen.io/NewbCake/pen/JvwNJq (垂直调整窗口大小以设置字体大小)

我愿意接受有关如何解决此问题或可能遇到的任何陷阱的任何建议。

HTML

<section class="center">
  <div class="container">
    <div class="item1">H</div>
    <div class="item2">H</div>
  </div>
</section>

CSS

section {
  display:flex;
  flex-direction:row;
  height:95vh;
  width:100%;
  border:1px solid red;
}

.container {
  display:flex;
  flex-direction:column;
  height:80vh;
  width:80vh;
  border:1px solid blue;
}

.container_wide {
  display:flex;
  flex-direction:column;
  height:80vh;
  width:80vh;
  border:1px solid blue;
}

.center {
  justify-content:center;
  align-items:center;
}

.item1 {
  flex-grow:1;
  flex-shrink:0;
  flex-basis:auto;
  border:1px solid green;
  line-height:.75;
}

.item2 {
  flex-grow:3;
  flex-shrink:0;
  flex-basis:auto;
  border:1px solid green;
  line-height:.75;
}

JS

var resizeTimer;

$(window).on('resize', function(e) {

  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(function() {

    // Run code here, resizing has "stopped"
    $(".item1").css("font-size", $(".item1").css("height"));
    $(".item2").css("font-size", $(".item2").css("height"));            
  }, 250);
});

任何帮助表示赞赏!

标签: jqueryhtmlcssflexboxfont-size

解决方案


如果您有控制权,flex-grow您可以font-size根据容器的高度进行一些计算。因此,如果您有1 + 2as flex-grow,则意味着第二个将是第一个的两倍,因此我们可以将H高度定义为H+2*H = height of container = 80vhso H = calc(80vh / 3)

所以第一个项目将有font-size:H,第二个项目将有font-size:2*H

您也可以考虑使用 CSS 变量来更好地处理这个问题。

body {
   margin:0;
  padding:0;
  font-family: sans-serif;
}

header {
  display:flex;
  height:5vh;
}
section {
  display:flex;
  flex-direction:row;
  height:95vh;
  width:100%;
  border:1px solid red;
}

.container {
  display:flex;
  flex-direction:column;
  --h:80vh;
  height:var(--h);
  width:var(--h);
  border:1px solid blue;
}

.gauge {
  display:flex;
  flex-direction:column;
  height:80vh;
  width:10vh;
  border:1px solid blue;
}

.center {
  justify-content:center;
  align-items:center;
}

.item1 {
  flex-grow:1;
  font-size:calc((var(--h) / 3));
  flex-shrink:0;
  flex-basis:auto;
  border:1px solid green;
  line-height:1;
}

.item2 {
  font-size:calc((var(--h) / 3) * 2);
  flex-grow:2;
  flex-shrink:0;
  flex-basis:auto;
  border:1px solid green;
  line-height:1;
}
<header class="center">resize window vertically</header>
<section class="center">
  <div class="gauge">
    <div class="item1"></div>
    <div class="item2"></div>
  </div>
  <div class="container">
    <div class="item1">Haj</div>
    <div class="item2">Hlp</div>
  </div>
</section>


推荐阅读