使用 CSS/jQuery 的响应式字体大小 [英] Responsive font size using CSS/jQuery

查看:18
本文介绍了使用 CSS/jQuery 的响应式字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 div 中创建响应式文本.

我尝试了 jquery-textfillFlowType,但它们根本不适合我.

FlowType 不会使用所有可用空间,只会使用其中的一部分(demo),而 textfill 不考虑高度(demo).

我是否错误地使用了它们,或者我想要的东西太难实现?

我的 HTML:

<div class="external"><div class="internal">示例</div>

我的 CSS:

.internal{width:100%;height:100%}.外部{宽度:400像素;高度:50像素;}

附注.目前对视口的支持不够.

解决方案

更新了 resize 事件侦听器.更新了 fiddle.

据我所知,您希望文本尽可能大,同时仍然适合包含在

中的内容,对吗?我的解决办法是在文本周围放一个,符合文本的正常大小.然后计算容器的尺寸与 的尺寸之间的比率.以较小的比例(宽度或高度)为准,使用该比例放大文本.

HTML:

<span class="text-fitter">在这打字</span>

JS(jQuery):

textfit();$(window).on('resize', textfit);函数 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 约束 = Math.min(wRatio, hRatio);$('.text-fitter').css('font-size',constraint + 'em');}

这是一个小提琴.调整 CSS 中的 .container 尺寸以查看其实际效果.

I want to create a responsive text inside a div.

I tried jquery-textfill and FlowType, but they are not working for me at all.

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?

My HTML:

<body>
    <div class="external">
        <div class="internal">Example</div>
    </div>    
</body>

My CSS:

.internal{width:100%;height:100%}
.external{width:400px;height:50px;}

PS. Viewports are not supported enough for now.

解决方案

EDIT: Updated with resize event listener. Updated fiddle.

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):

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');
}

Here's a fiddle. Adjust the .container dimensions in the CSS to see it in action.

这篇关于使用 CSS/jQuery 的响应式字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆