[英]CSS/JS - Overriding font-size if the word is too long for the container
[英]Reduce font-size when long word overflows horizontally
我的长标题有时会在小屏幕上使窗口稍微溢出,因此我编写了一个脚本来减小标题的字体大小,直到只有当标题溢出其容器时才适合它的容器 ……它可以工作,但我敢肯定它会更轻可以找到解决方案。
function adaptFontSize(titles) {
$(titles).each(function() {
var title = $(this),
reducedFontSize,
counter = 0;
if (title[0].scrollWidth <= title.innerWidth()) { // if title <= container
title.css('font-size', ''); // remove previously added font-size
}
while (title[0].scrollWidth > title.innerWidth() && counter < 20) { // while title > container
var fontSize = reducedFontSize || parseInt(title.css('font-size')); // current title font-size
reducedFontSize = Math.floor((fontSize - fontSize / 20) * 100) / 100; // reduce the font-size
title.css('font-size', reducedFontSize + 'px'); // apply the reduced font-size
counter++ // counter to limit the loop in case title[0].scrollWidth is not supported
}
});
}
或者这是一个JSFiddle: https ://jsfiddle.net/Raoulito/pek7b3mr/12/
当我尝试在
$(window).resize()
上应用脚本时,出现了我的问题。 它确实有效,但是我可以感觉到过程很繁琐。 它必须同时以两种方式工作:
- 如果标题太宽,请减小字体大小,
- 当窗口变大时,增加字体大小, 直到标题达到其原始字体大小 。
以下是我尝试但无法实现的一些步骤:
因此,我正在寻找一种方法来解决这些问题,或者寻找一种更有效的方法来解决这些问题。
您可以使用VW单元 。
1vw
等于视图宽度的1%
,因此这是一个仅适用于CSS的简单解决方案,可在所有现代浏览器中使用。
https://jsfiddle.net/pek7b3mr/8/
body { margin: 1em; font-family: sans-serif; } div { background-color: yellow; font-size: 5vw; margin-bottom: 1rem; }
<div>ABCDEFGHIJKLMNOPQRSTUVWXYZ 012356789</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.