Javascript 如何根据容器大小设置字体大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10292001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:42:50  来源:igfitidea点击:

how to set font size based on container size?

javascriptcssfont-size

提问by FurtiveFelon

I have a container that has a % width and height, so it scales depending on external factors. I would like the font inside the container to be a constant size relative to the size of containers. Is there any good way to do this using CSS? The font-size: x%would only scale the font according to the original font size (which would be 100%).

我有一个具有 % 宽度和高度的容器,因此它会根据外部因素进行缩放。我希望容器内的字体相对于容器的大小是一个恒定的大小。有什么好的方法可以使用 CSS 做到这一点吗?将font-size: x%根据原来的字体尺寸(这将是100%)将只缩放字体。

采纳答案by Matthew Riches

You may be able to do this with CSS3 using calculations, however it would most likely be safer to use JavaScript.

您可以使用 CSS3 使用计算来做到这一点,但使用 JavaScript 很可能更安全。

Here is an example: http://jsfiddle.net/8TrTU/

这是一个例子:http: //jsfiddle.net/8TrTU/

Using JS you can change the height of the text, then simply bind this same calculation to a resize event, during resize so it scales while the user is making adjustments, or however you are allowing resizing of your elements.

使用 JS,您可以更改文本的高度,然后简单地将相同的计算绑定到调整大小事件,在调整大小期间,以便在用户进行调整时进行缩放,或者您允许调整元素的大小。

回答by

If you want to set the font-size as a percentage of the viewport width, use the vwunit:

如果要将字体大小设置为视口宽度的百分比,请使用vw单位:

#mydiv { font-size: 5vw; }

The other alternative is to use SVG embedded in the HTML. It will just be a few lines. The font-size attribute to the text element will be interpreted as "user units", for instance those the viewport is defined in terms of. So if you define viewport as 0 0 100 100, then a font-size of 1 will be one one-hundredth of the size of the svg element.

另一种选择是使用嵌入在 HTML 中的 SVG。这将只是几行。文本元素的 font-size 属性将被解释为“用户单位”,例如视口是根据其定义的。因此,如果您将视口定义为 0 0 100 100,那么字体大小 1 将是 svg 元素大小的百分之一。

And no, there is no way to do this in CSS using calculations. The problem is that percentages used for font-size, including percentages inside a calculation, are interpreted in terms of the inherited font size, not the size of the container. CSS could use a unit called bw(box-width) for this purpose, so you could say div { font-size: 5bw; }, but I've never heard this proposed.

不,没有办法在 CSS 中使用计算来做到这一点。问题在于用于字体大小的百分比,包括计算中的百分比,是根据继承的字体大小而不是容器的大小来解释的。bw为此,CSS 可以使用一个名为(box-width)的单位,因此您可以说div { font-size: 5bw; },但我从未听说过有人提议这样做。

回答by apaul

Another js alternative:

另一个 js 替代方案:

Working Example

工作示例

fontsize = function () {
    var fontSize = $("#container").width() * 0.10; // 10% of container width
    $("#container h1").css('font-size', fontSize);
};
$(window).resize(fontsize);
$(document).ready(fontsize);

Or as stated in torazaburo's answeryou could use svg. I put together a simple example as a proof of concept:

或者如torazaburo 的回答中所述,您可以使用 svg。我整理了一个简单的例子作为概念证明:

SVG Example

SVG 示例

<div id="container">
    <svg width="100%" height="100%" viewBox="0 0 13 15">
        <text x="0" y="13">X</text>
    </svg>
</div>

回答by ElvinD

I used Fittexton some of my projects and it looks like a good solution to a problem like this.

我在我的一些项目中使用了Fittext,它看起来是解决此类问题的好方法。

FitText makes font-sizes flexible. Use this plugin on your fluid or responsive layout to achieve scalable headlines that fill the width of a parent element.

FitText 使字体大小灵活。在您的流畅或响应式布局上使用此插件来实现填充父元素宽度的可扩展标题。

回答by o.v.

It cannotbe accomplished with css font-size

不能用 css font-size来完成

Assuming that "external factors" you are referring to could be picked up by media queries, you could use them - adjustments will likely have to be limited to a set of predefined sizes.

假设您所指的“外部因素”可以被媒体查询获取,您可以使用它们 - 调整可能必须限于一组预定义的大小。

回答by tnt-rox

Here is the function:

这是函数:

document.body.setScaledFont = function(f) {
  var s = this.offsetWidth, fs = s * f;
  this.style.fontSize = fs + '%';
  return this
};

Then convert all your documents child element font sizes to em's or %.

然后将所有文档子元素字体大小转换为 em 或 %。

Then add something like this to your code to set the base font size.

然后将类似的内容添加到您的代码中以设置基本字体大小。

document.body.setScaledFont(0.35);
window.onresize = function() {
    document.body.setScaledFont(0.35);
}

http://jsfiddle.net/0tpvccjt/

http://jsfiddle.net/0tpvccjt/

回答by Richard Merchant

I had a similar issue but I had to consider other issues that @apaul34208 example did not tackle. In my case;

我有一个类似的问题,但我不得不考虑@apaul34208 示例没有解决的其他问题。就我而言;

  • I have a container that changed size depending on the viewport using media queries
  • Text inside is dynamically generated
  • I want to scale up as well as down
  • 我有一个容器,它根据使用媒体查询的视口改变大小
  • 里面的文字是动态生成的
  • 我想放大和缩小

Not the most elegant of examples but it does the trick for me. Consider using throttling the window resize (https://lodash.com/)

不是最优雅的例子,但它对我有用。考虑使用限制调整窗口大小 ( https://lodash.com/)

var TextFit = function(){
 var container = $('.container');
  container.each(function(){
    var container_width = $(this).width(),
      width_offset = parseInt($(this).data('width-offset')),
        font_container = $(this).find('.font-container');
 
     if ( width_offset > 0 ) {
         container_width -= width_offset;
     }
                
    font_container.each(function(){
      var font_container_width = $(this).width(),
          font_size = parseFloat( $(this).css('font-size') );

      var diff = Math.max(container_width, font_container_width) - Math.min(container_width, font_container_width);
 
      var diff_percentage = Math.round( ( diff / Math.max(container_width, font_container_width) ) * 100 );
      
      if (diff_percentage !== 0){
          if ( container_width > font_container_width ) {
            new_font_size = font_size + Math.round( ( font_size / 100 ) * diff_percentage );
          } else if ( container_width < font_container_width ) {
            new_font_size = font_size - Math.round( ( font_size / 100 ) * diff_percentage );
          }
      }
      $(this).css('font-size', new_font_size + 'px');
    });
  });
}

$(function(){
  TextFit();
  $(window).resize(function(){
   TextFit();
  });
});
.container {
  width:341px;
  height:341px;
  background-color:#000;
  padding:20px;
 }
 .font-container {
  font-size:131px;
  text-align:center;
  color:#fff;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="container" data-width-offset="10">
 <span class="font-container">£5000</span>
</div>

https://jsfiddle.net/Merch80/b8hoctfb/7/

https://jsfiddle.net/Merch80/b8hoctfb/7/

回答by pomber

If you want to scale it depending on the element width, you can use this web component:
https://github.com/pomber/full-width-text

如果你想根据元素宽度缩放它,你可以使用这个 web 组件:https:
//github.com/pomber/full-width-text

Check the demo here:
https://pomber.github.io/full-width-text/

在此处查看演示:https:
//pomber.github.io/full-width-text/

The usage is like this:

用法是这样的:

<full-width-text>Lorem Ipsum</full-width-text>

回答by ScottS

I've given a more detailed answer of using vwwith respect to specific container sizing in this answer, so I won't just repeat my answer here.

我已经在这个答案中给出了关于使用vw特定容器大小的更详细的答案,所以我不会在这里重复我的答案。

In summary, however, it is essentially a matter of factoring (or controlling) what the container size is going to be with respect to viewport, and then working out the proper vwsizing based on that for the container, taking mind of what needs to happen if something is dynamically resized.

然而,总而言之,它本质上是一个分解(或控制)容器尺寸相对于视口的问题,然后vw根据容器的尺寸确定合适的尺寸,考虑需要发生的事情如果某些东西是动态调整大小的。

So if you wanted a 5vwsize at a container at 100% of the viewport width, then one at 75%of the viewport width you would probably want to be (5vw * .75) = 3.75vw.

因此,如果您希望5vw容器的大小为视口宽度的 100%,那么75%您可能希望将视口宽度设为(5vw * .75) = 3.75vw.

回答by Angie

You can also try this pure CSS method:

你也可以试试这个纯 CSS 方法:

font-size: calc(100% - 0.3em);