繁体   English   中英

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

[英]How to: Reduce font-size if a line breaks

我有一个div内的跨度,div必须保持200px宽,文本必须适合div中的一行。 跨度中的文本是动态生成的,因此我不可能知道哪些内容会中断到新行,哪些内容不会。

 <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/

试试这个并添加文字以查看结果

<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>

一个非常具体的案例 - 如果您有固定的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类,它将调用你定义的这个函数,所以你的类“long-word-title”可以在需要的地方应用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM