Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create truely responsive typography in CSS3 relative to screen width

Imagine you have a container div:

.container {
  max-width: 95%;
  margin-right: auto;
  margin-left: auto;
}

This creates a lovely, fully responsive left and right margin, proportionate to any browser screen width, right?

For extra small and extra large screens, you can even add a couple of @media queries to bound it, so the content is always readable:

@media (min-width: 450px) {
  .container {
  max-width: 100% // Remove the padding
  }
}

@ media (min-width: 1170px) {
  .container { max-width: 1170px // Prevent your content scaling to infinity
  }
}

Now imagine you wanted to have the same principals applied to typography and font sizes.

A relative % font size with min and max values, proportionate to screen width. I'm not talking about lots of jumpy static @media queries (as say, ahem BS3 relies), but a smooth transition, just like the container above.

And I want to do it without javascript (boo! no lettering.js!). Any CSS3 gurus out there?

Answers on a postcard please.

like image 406
alias51 Avatar asked Feb 16 '23 12:02

alias51


1 Answers

There newer methods emerging using relative units (vw/vh/vmax/vmin) a good article for this is: http://snook.ca/archives/html_and_css/vm-vh-units

however, this is still not widely supported. The best method I've found is applying font adjustments per resolution to the html selector (example below). You only declare the base font-size at the mobile view and progressively enhance using "rem" values (which are relative to the root selector).

Caveat to this, lte IE 8, Opera Mini, and iOS Safari 3.2 doesn't support the rem value, IE 9/10 doesn't support it in the shorthand "font" property. So it depends on your browser support needs. Using px values as fallbacks defeats the purpose of the relative units so... unless you're using modernizr's .no-cssremvalue to specify px units as fallbacks, and then you should be using modernizr to check for vw/vh/vmax/vmin support anyways.

alternate methods:

I'd also look into the Zurb Foundation 5's front-end framework as they've used a rather interesting method using meta tags to adjust the font-sizes responsively. http://foundation.zurb.com/docs/components/global.html

There are js libraries like flowtype.js and a few others as well, just look around (lots of new stuff out there since Aug '13)

:root { font-size:68.75% }

  body{ font-size:1rem; /*IE9 & 10*/
        line-height:1.625; /*IE9 & 10*/
        font:1rem/1.625 sans-serif }

    h1{ font-size:2.9375rem }
    h2{ font-size:1.8125rem }
    h3{ font-size:1.4375rem }

@media (min-width:30rem){     :root{ font-size:81.25% } }
@media (min-width:37.5em){    :root{ font-size:93.75% } }
@media (min-width:50em){      :root{ font-size:112.5% } }
@media (min-width:62.4375em){ :root{ font-size:118.75% } }

/* etc. */
like image 57
darcher Avatar answered Apr 29 '23 20:04

darcher