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

Exc*_*tSP 11 html javascript css jquery

我有一个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>
Run Code Online (Sandbox Code Playgroud)

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

如何根据线路是否中断减少字体大小(或缩放)?我更喜欢CSS答案,但我理解这是否超出了CSS的能力.

Ale*_* K. 11

一个相当讨厌的方法:循环减少溢出的跨度,直到它小于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");
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


hop*_*att 5

我建议阅读 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
Run Code Online (Sandbox Code Playgroud)

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

  • 但这是相对于视口的,而不是特定元素。不确定这是否是OP所期望的 (2认同)