如何:如果换行,请减小字体大小

How to: Reduce font-size if a line breaks

本文关键字:字体 如果 换行 如何      更新时间:2023-10-02

我在div中有一个span,div必须保持200px宽,文本必须放在div中的一行上。span中的文本是动态生成的,所以我不可能知道哪些内容会换行,哪些不会换行。

<div style="width:200px">
  <span style="font-size:12px;">This sentence is too large to fit within the div.</span>
</div>

如果我使用CSS属性white-space:nowrap;,单词将溢出到div的外部,这当然是我们不希望的。

如何根据换行与否来减小字体大小(或缩放)?我更喜欢CSS的答案,但我理解这是否超出了CSS的能力。

一种相当讨厌的方法:循环减少溢出跨度,直到其小于div宽度;

var divWidth = $("#theDiv").width();
var text = $("#text");
var fontSize = 12;
while (text.width() > divWidth)
  text.css("font-size", fontSize -= 0.5);
text.css("display", "inline");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="theDiv" style="width:200px; border:1px solid red;">
  <span id="text" style="display:none;white-space:nowrap;">This sentence is too large to fit within the div.</span>
</div>

我建议阅读CSS视口单元。这可能是一个很好的解决方案,就像你在纯CSS中找到的一样。

1vw = 1% of viewport width
1vh = 1% of viewport height
1vmin = 1vw or 1vh, whichever is smaller
1vmax = 1vw or 1vh, whichever is larger

http://css-tricks.com/viewport-sized-typography/

一个非常特殊的情况-如果您有固定的div大小并使用Angular.js:

  1. 定义一个函数来测试是否有一个单词将被换行(因为你知道一行可以包含多少个字符),并返回一个字符串来指定一个字体较小的css类:

    $scope.longWordSubstepTitleResize = function(title){
        var longestWord = title.split(' ').reduce(function(longest, currentWord) {
            return currentWord.length > longest.length ? currentWord : longest;
        }, "");
        if (longestWord.length>13){
            return "long-word-title";
        }else{
            return;
        }
    }
    
  2. 在你的模板中,添加一个css类,它将调用你定义的这个函数,这样你的类"长单词标题"就可以在需要的地方应用:

    <div class="noselect sub-step-title {{longWordSubstepTitleResize(title)}}">
    
  3. 将较小文本的css规则添加到样式表

尝试并添加文本以查看结果

<HTML>
<HEAD>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){
    var count = $("span").text().length;
    var y = 1000/count ;
    $('span').css('font-size',y);
  });

</script>
</HEAD>
<BODY>
   <div style="width:200px; border:1px solid black;">
<span style="font-size:12px;">This sentence is too large to fit within the div</span>
</div>