最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Font-size that expands when you resize the window - Stack Overflow

programmeradmin3浏览0评论

How do I make my font in HTML such that when I expand the window, the size of the text expands also. Sort of like setting a percentage for the text that will take on a percentage of the size of the box it is in.

Here is an illustration of what I would like to happen:

#box #text {
   font-size: 50%;
}

Now lets say #box is 200px, #text should be 100px. Obviously I can't just put a fix width for #text because in the site #box will be a dynamic width.

How do I make my font in HTML such that when I expand the window, the size of the text expands also. Sort of like setting a percentage for the text that will take on a percentage of the size of the box it is in.

Here is an illustration of what I would like to happen:

#box #text {
   font-size: 50%;
}

Now lets say #box is 200px, #text should be 100px. Obviously I can't just put a fix width for #text because in the site #box will be a dynamic width.

Share Improve this question asked Jun 1, 2011 at 20:12 ChaimChaim 2,1494 gold badges27 silver badges48 bronze badges 4
  • 1 As an ID is unique, there's no need to put #text besides #box in your css declaration. Just write #text as no other element is supposed to get this ID – ecchymose Commented Jun 1, 2011 at 20:15
  • Okay, I understand that. I was just doing it like that to illustrate that #text was inside #box – Chaim Commented Jun 1, 2011 at 20:18
  • @ecchymose: And, what if I use one css file for many html pages? – Chaim Commented Jun 2, 2011 at 16:03
  • 1 Then you're right I think! If you can have #text inside #box in page A, but #text inside #box2 in page B, I guess you can be specific and declare "#box #text" on one line and "#box2 #text" after. – ecchymose Commented Jun 2, 2011 at 16:25
Add a comment  | 

3 Answers 3

Reset to default 9

Do it in jquery.

$(window).resize(function(){
    $('#box #text').css('font-size',($(window).width()*0.5)+'px');
});

Use the vh (viewport height), vw (viewport width), and/or vm (viewport minimum (smallest of the dimensions)) units in browsers that fully support CSS3, and for other browsers listen for resize and JavaScript such as in Razor Storm's answer.

In browsers that support it, you can use CSS media queries to change your layout depending on the width of the window.

发布评论

评论列表(0)

  1. 暂无评论