根据容器高度创建动态字体大小:我做错了什么?

时间:2015-08-11 18:53:49

标签: javascript jquery html css responsive-design

情况:

我正在尝试强制文本的font-size与容器的高度成比例,这样它就像文本一样,是背景图像的一部分。我正在通过为font-size中的px提供height,其em的1/20(大约现在),然后根据{{定义后代文本元素1}}。

HTML

<div id="front-page-blue-strip">
    <h1>Here's my title</h1>
    <p>Here's the text under my title</h1>
</div>

CSS

#front-page-blue-strip h1 { font-size: 1.5em;}
#front-page-blue-strip p  { font-size: 0.9em;}

JS

$(window).resize(function(){
      $('#front-page-blue-strip').attr('font-size', ($(this).height() / 20).toString() + 'px');     
});

现在我已确认font-size的{​​{1}}正在按计划重新调整,但内部#front-page-blue-stripfont-size元素的h1是不。我做错了什么?

2 个答案:

答案 0 :(得分:1)

$('#front-page-blue-strip').attr('font-size', ($(this).height() / 20).toString() + 'px');

通过执行此操作,您只需将属性添加到未预定义的元素 property,而不是预定义属性style之一的属性。

相反尝试这个

$('#front-page-blue-strip').css('font-size', ($(this).height() / 20).toString() + 'px');

$('#front-page-blue-strip')
 .attr('style','font-size:'+ ($(this).height() / 20).toString() + 'px');

答案 1 :(得分:1)

font-size需要进入style属性。你可以使用jQuery的.css()函数:

来实现
$(window).resize(function(){
      $('#front-page-blue-strip').css('font-size', ($(this).height() / 20).toString() + 'px');     
});

JSFiddle

相关问题