Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can font-size be a % of container size in css/css3?

Tags:

css

font-size

I have a container:

<div id="container"><h1>LONG TITLE LINE</h1></div>

and css:

#container {
    width: 50%;
    height: 50%;
}

#container h1 {
    font-size: XXXXXX;
}

"XXXXXX" <-- where i want the font size to be based on the width of the page/container.


QUESTION: is it possible to have the font-size of the h1 based on the width of the page? in css3? i'm sure it can be done using JS, but like to avoid that if it is possible.

like image 253
circusdei Avatar asked Jan 26 '12 16:01

circusdei


People also ask

How do you change the font-size based on container width?

The font size can be set with vw (viewport) unit, which means the viewport width. The viewport is the browser window size. 1vw = 1% of viewport width. If the viewport is 50cm wide, 1vw is 0.5cm.

How do I fix the container size in CSS?

Using width, max-width and margin: auto; Then, you can set the margins to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins: This <div> element has a width of 500px, and margin set to auto.

Which value of the font-size is the same as 100% in CSS?

First and foremost, the current font-size is equal to 100% (i.e. 12pt = 100%).

Which is the correct way of using font-size in CSS?

For example, suppose the font-size of the <body> of the page is set to 16px . If the font-size you want is 12px , then you should specify 0.75em (because 12/16 = 0.75). Similarly, if you want a font size of 10px , then specify 0.625em (10/16 = 0.625); for 22px , specify 1.375em (22/16).


2 Answers

I don't think it's possible in CSS, but this might be interesting to you:

http://fittextjs.com/

like image 130
Jason Goldstein Avatar answered Sep 30 '22 11:09

Jason Goldstein


An other option dependng on your layout is to use vw units :

vw : 1/100th of the width of the viewport.(source MDN)

If your #container width is set as a percentage of the viewport, font-size will adapt to it's width :

DEMO

CSS :

#container h1 {
    font-size: 5vw;
}

Browser support for vw units is IE9+, see canIuse for more info.

like image 24
web-tiki Avatar answered Sep 30 '22 13:09

web-tiki