问题描述
我有一个固定高度和流畅宽度( body
width的15%)的 div
。我想让段落文本里面完全填充 div
;
I have a div
with a fixed height and a fluid width (15% of body
width). I want the paragraph text inside to totally fill the div
; not overflow and not underfill.
我尝试使用jQuery来增加文本大小,直到段落的高度等于容器的高度 div
。在这一点上,文本应该完全覆盖 div
。唯一的问题是font-size以0.5px的值递增。你不能做33.3px;它必须是33.0像素或33.5像素。所以在33px,我的文本太短,不能覆盖 div
,在33.5px它溢出。
I've tried with jQuery to increment the text size until the height of the paragraph is equal to the height of the container div
. At that point, the text should be totally covering the div
. The only problem is that font-size increments in 0.5px values. You can't do 33.3px; it has to be either 33.0px or 33.5px. So at 33px, my text is far too short to cover the div
, and at 33.5px it overflows.
有没有人有任何想法如何补救这一点?有很多插件用于使文本填充容器的整个宽度,但不能用于必须填充宽度和高度的文本。至少,我没见过。
Does anyone have any ideas on how to remedy this? There are lots of plugins for making text fill the whole width of a container, but not for text that has to fill both the width and height. At least, none that I've seen.
<head>
<style type="text/css">
.box {
display:block;
position:relative;
width:15%;
height:500px;
background:orange;
}
.box p {
background:rgba(0,0,0,.1); /* For clarity */
}
</style>
</head>
<body>
<div class="box">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. <br><br>
Suspendisse varius nibh quis urna porttitor, pharetra elementum nisl egestas. Suspendisse libero lacus, faucibus id convallis sit amet, consequat vitae odio.</p>
</div>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
function responsiveText(){
var i = 0.5;
do {
$(".box p").css("font-size",(i) + "px");
var textHeight = $(".box p").height(),
containerHeight = $(".box").height();
i += 0.5;
} while ( textHeight < containerHeight ); // While the height of the paragraph block is less than the height of the container, run the do...while loop.
} responsiveText();
$(window).resize(function(e) {
responsiveText();
});
</script>
</body>
文本设置为33px。
Text set at 33px. It is too short.
文本设置为33.5像素。它溢出。
Text set at 33.5px. It overflows.
推荐答案
使用 em
单位,而不是 px
从0.5到0.003。
I adjusted your function to use em
units instead of px
, and adjusted the increment from "0.5" to "0.003".
预览窗格有点不可靠,因此。
The preview pane is a little unreliable, so check it out in its own window.
请注意:
- 增量越大,循环迭代次数越少(
处理的次数越少)。 - 增量,更精细调整
和结果。
这篇关于调整文本大小以完全填充容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!