Javascript HTML / CSS - 调整字体大小以填充父级的高度和宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7826086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML / CSS - adjust font-size to fill parent height and width
提问by Web_Designer
I have a <div>
element that resizes as the browser window resizes.
我有一个<div>
随着浏览器窗口调整大小而调整大小的元素。
Inside the <div>
I have a paragraph of text:
在里面<div>
我有一段文字:
<div style="width:80%; height:80%; margin:10%;">
<p>Paragraph of text. Paragraph of text. Paragraph of text.</p>
</div>
I want the text to change font-size
as I resize the <div>
, so that the text will occuypy 100% of the available space.
我希望文本在font-size
我调整大小时发生变化<div>
,以便文本将占用 100% 的可用空间。
How can I achieve this effect?
Would it be with a percentage font-size?
Would I have to use Javascript?
我怎样才能达到这种效果?
它会带有百分比字体大小吗?
我必须使用 Javascript 吗?
Thanks in advance!
提前致谢!
回答by Bas
There's a jquery plugin for this: http://fittextjs.com/
有一个 jquery 插件:http: //fittextjs.com/
回答by Nick
回答by Zefir Zdravkov
What you need is called vw
. Example CSS: font-size: 80vw;
. vw
means viewerport width, and 80vw
= 80%
of the device screen width
你需要的叫做vw
. 例如CSS:font-size: 80vw;
。vw
表示视窗宽度,和80vw
=80%
设备屏幕宽度
回答by Jawad
HTML
HTML
<div id="change" style="margin:10%;">
<p>Paragraph of text. Paragraph of text. Paragraph of text.</p>
</div>
CSS
CSS
#change {
width: 80%;
height: 80%;
border: 1px solid black;
overflow: hidden;
font-size: 1em;
}
JAVASCRIPT
爪哇脚本
$(function() {
while( $('#change div').height() > $('#change').height() ) {
$('#change div').css('font-size', (parseInt($('#change div').css('font-size')) - 1) + "px" );
}
});
回答by Martin Adámek
fittext.js
did not work correctly for me (plugin for jQuery, as well as derived jquery-free version), nor with using of compressor attribute, so I found another solution:
fittext.js
对我来说不能正常工作(jQuery 插件,以及派生的 jquery-free 版本),也不能使用压缩器属性,所以我找到了另一个解决方案:
http://www.dhtmlgoodies.com/?whichScript=text_fit_in_box(someone's another work)
http://www.dhtmlgoodies.com/?whichScript=text_fit_in_box(某人的另一部作品)
which works perfectly for me - longer texts as well as shorter texts.
这对我来说非常适合 - 较长的文本和较短的文本。
It just do not react to resize of window (it works just once on loading of page), so I have written this short code to run it automatically after each window resize (it works for me):
它只是对窗口大小的调整没有反应(它在页面加载时只工作一次),所以我写了这个简短的代码来在每个窗口调整大小后自动运行它(它对我有用):
<script>
function calculate_font_sizes()
{
fitTextInBox('login-h1');
fitTextInBox('subtittle');
}
calculate_font_sizes();
window.addEventListener('resize', calculate_font_sizes);
</script>
I hope it can help to someone.
我希望它可以帮助某人。