使用CSS/jQuery的自适应字体大小 [英] Responsive font size using CSS/jQuery
问题描述
我想在div内创建一个响应文本.
I want to create a responsive text inside a div.
我尝试了 jquery-textfill 和
I tried jquery-textfill and FlowType, but they are not working for me at all.
FlowType 不使用所有可用空间,仅使用其中一部分(演示),而 textfill 不考虑高度(演示 ).
FlowType does not use all the available space, only a part of it (demo), while textfill does not respect the height (demo).
我使用它们的方式不正确吗?或者我想要实现的目标太难了?
Am I using them incorrecly or what I want is too hard to achieve?
我的HTML:
<body>
<div class="external">
<div class="internal">Example</div>
</div>
</body>
我的CSS:
.internal{width:100%;height:100%}
.external{width:400px;height:50px;}
PS.目前,视口还不够受支持.
PS. Viewports are not supported enough for now.
推荐答案
已使用resize
事件侦听器更新.已更新小提琴.
Updated with resize
event listener. Updated fiddle.
据我了解,您希望文本尽可能大,同时仍适合包含的<div>
,对吗?我的解决方案是在文本周围放置一个<span>
,它与文本的正常大小一致.然后计算容器尺寸和<span>
尺寸之间的比率.较小的比例(宽度或高度)中的较大比例,请使用该比例放大文本.
As I understand it, you want the text to be as large as possible while still fitting inside the containing <div>
, correct? My solution is to put a <span>
around the text, which conforms to the text's normal size. Then calculate the ratios between the container's dimensions and the <span>
's dimensions. Whichever is the smaller ratio (either width or height), use that ratio to enlarge the text.
HTML:
<div class="container">
<span class="text-fitter">
text here
</span>
</div>
JS(jQuery):
JS (jQuery):
textfit();
$(window).on('resize', textfit);
function textfit() {
$('.text-fitter').css('font-size', 'medium');
var w1 = $('.container').width()-10;
var w2 = $('.text-fitter').width();
var wRatio = Math.round(w1 / w2 * 10) / 10;
var h1 = $('.container').height()-10;
var h2 = $('.text-fitter').height();
var hRatio = Math.round(h1 / h2 * 10) / 10;
var constraint = Math.min(wRatio, hRatio);
$('.text-fitter').css('font-size', constraint + 'em');
}
这是小提琴.调整CSS中的.container
尺寸以查看其作用.
Here's a fiddle. Adjust the .container
dimensions in the CSS to see it in action.
这篇关于使用CSS/jQuery的自适应字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!