我有一段文字。当文本长度增加时,我不想溢出额外的页面。需要始终打印一页。
当文本大小大于div的大小时,是否可以在div中使用css自动缩放文本的字体大小?
文本将由用户编写。我对文本长度没有任何想法。但我不想让他们使用一页以上的页面。可以设置div的大小,但不能设置文本的长度。最好的方法是什么?
根据您的评论,您愿意使用 Javascript,因此提出了 Javascript 解决方案(实际上使用 jQuery)。希望您明白,仅使用 CSS 是不可能做到这一点的。
您所需要的只是定义 的阈值height。例如,如果您决定需要将文本容纳在p最大高度为 的a 中100px,则循环并不断减小font-size直到达到阈值高度。
像这样的东西:
var threshold = 100, /* define height to restrict */
p = $('#p'), /* your element depending on whatever selector */
fs = parseInt(p.css('font-size')); /* get the current font size */
while (p.height() > threshold) { /* while height is more than threshold */
p.css({'font-size': fs-- }); /* reduce the font-size */
}
p.height(threshold); /* adjust the final height to clean up */
Run Code Online (Sandbox Code Playgroud)
您可能需要在循环后稍微调整最终高度。
演示小提琴:http://jsfiddle.net/abhitalks/ab6m7yh1/2/
演示片段:
var threshold = 100, /* define height to restrict */
p = $('#p'), /* your element depending on whatever selector */
fs = parseInt(p.css('font-size')); /* get the current font size */
while (p.height() > threshold) { /* while height is more than threshold */
p.css({'font-size': fs-- }); /* reduce the font-size */
}
p.height(threshold); /* adjust the final height to clean up */
Run Code Online (Sandbox Code Playgroud)
var threshold = 100;
$('p').each(function() {
var $self = $(this),
fs = parseInt($self.css('font-size'));
while($self.height() > threshold) {
$self.css({'font-size': fs-- });
}
$self.height(threshold);
});Run Code Online (Sandbox Code Playgroud)
p { font-size: 2em; width: 320px; height: auto; border: 1px solid #ccc; }Run Code Online (Sandbox Code Playgroud)