set font-size according to the body width with css3
10,415
If your <body>
tag has the same width as the viewport, you can use vw
units :
vw : 1/100th of the width of the viewport.( source MDN)
body{
font-size:5vw;
}
If your <body>
tag has a percentage width, vw
units will work too (considering the <html>
tag doesn't have a fixed width).
Example :
body{
width:50%; /* = 100% / 2 */
font-size:2.5vw; /* = 5vw / 2 */
}
If your body tag has a fixed width (in px, em... units), font-size set with vw
won't adapt to it's width.
Browser support for vw units is IE9+, canIuse for more info.
Comments
-
Alfred Huang almost 2 years
I want to set the
font-size
of<body>
to be 5% of the width of itself(body
).Is there a pure css3 way to do this?
I'm doing this with jquery now, but I want it simpler:
$(function() { var $body = $('body'); function adjust_font_size() { $body.css('font-size', $body.width()*0.05+'px'); } adjust_font_size(); $(window).resize(adjust_font_size); });
-
BoltClock almost 10 yearsThis depends on whether the OP actually meant to say "viewport" and not "body", unless they have a very specific reason to make the font size relative to the
body
element and not the viewport. I'm inclined to believe the former, even though the OP repeatedly makes references to thebody
element specifically. -
web-tiki almost 10 years@BoltClock I added some info about that in my answer.