[英]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
試試這個並添加文字以查看結果
<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:
定義一個函數,它將測試是否有一個將被包裝的單詞(因為你知道一行可以占用多少個字符)並返回一個字符串來指定一個字體較小的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; } }
在你的模板中,添加一個css類,它將調用你定義的這個函數,所以你的類“long-word-title”可以在需要的地方應用:
<div class="noselect sub-step-title {{longWordSubstepTitleResize(title)}}">
將較小文本的css規則添加到樣式表中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.