Change font size depending on resolution

Sonhja picture Sonhja · Jun 13, 2012 · Viewed 41.5k times · Source

I'm developing a Web page that uses different sizes for its different paragraphs, h... and so on. I'm using em sizes: font-size: 2em;, as an example. But when I change my screen resolution to a lower one, I want that size to a smaller one.

For that purpose, I tried this code:

<script>
        if ( screen.width > 1600)
        {
            document.write('<style>#centered h1 { font-size: 2em; } </style>');
        }
        else if (screen.width <= 1600 && screen.width >= 1360)
        {
            document.write('<style>#centered h1 { font-size: 1.7em; } </style>');
        }
        else if (screen.width < 1360 && >= 1024)
        {
            document.write('<style>#centered h1 { font-size: 1.4em; } </style>');
        }
        else
        {
            document.write('<style>#centered h1 { font-size: 0.8em; } </style>');
        }
    </script>

First: it doesn't work...
Second: I think there should be cleaner way to do so...

So, the question is: how to use different sizes to my fonts or how to make them adjust for different resolutions?

Can anyone help please? Thanks!

Answer

Vladimir Starkov picture Vladimir Starkov · Jun 13, 2012

Try to use this concept proof CSS:

html { font-size: 62.5%; }
body { font-size: 1em;}

@media (max-width: 300px) {
    html { font-size: 70%; }
}

@media (min-width: 500px) {
    html { font-size: 80%; }
}

@media (min-width: 700px) {
    html { font-size: 120%; }
}

@media (min-width: 1200px) {
    html { font-size: 200%; }
}

Working demo on jsFiddle