Francesca Francesca - 6 months ago 15
CSS Question

Font scaling based on width of container

I'm having a hard time getting my head around font scaling.

I currently have this site with a body

font-size
of 100%. 100% of what though? This seems to compute out at 16px.

I was under the impression that 100% would somehow refer to the size of the browser window, but apparently not because it's always 16px whether the window is resized down to a mobile width or full blown widescreen desktop.

How can I make the text on my site scale in relation to it's container? I tried using
em
but this doesn't scale either.

My reasoning is that things like my menu become squished when you resize, so I need to reduce the px
font-size
of
.menuItem
among other elements in relation to the width of the container. (E.g in the menu on a large desktop, 22px works perfectly. Move down to tablet width and 16px is more appropriate.)

I'm aware I can add break points, but I really want the text to scale as WELL has having extra breakpoints, otherwise I'll end up with hundreds of breakpoints for every 100px decrease in width to control the text.

Answer

What you are looking for is Viewport Percentage Units: http://dev.w3.org/csswg/css-values/#viewport-relative-lengths

The values are: ‘vw’ (viewport width), ‘vh’ (viewport height), ‘vmin’ (the smaller of vw or vh), ‘vmax’ (the larger or vw or vh).

1 v == 1% of the initial containing block

using it looks like this:

p {font-size: 4vw;}

As you can see, when the viewport width increases, so does the font-size, without media queries.

These values are a sizing unit just like px or em, so it can be used to size other elements as well, such was width, margin or padding.

Browser support is pretty good, but you'll likely need a fallback. Such as:

p {font-size: 16px; font-size: 4vw;}

Check out the support statistics: http://caniuse.com/#feat=viewport-units.

Also, check out CSS-tricks for a broader look: http://css-tricks.com/viewport-sized-typography/

EDIT

Here's a nice article about setting min/max sizes and exercising a bit more control over the sizes: http://madebymike.com.au/writing/precise-control-responsive-typography/

And here's an article about setting your size using calc() so that the text fills the viewport: http://codepen.io/CrocoDillon/pen/fBJxu

EDIT 2

Also, please view this article on csstricks.com which uses a technique dubbed 'molten leading' to adjust the line-height as well. https://css-tricks.com/molten-leading-css/