how to change the font-size proportionally to the change size of the window in CSS3 or javascript

The ideal way to do this is using the vw unit, which is defined as 1/100th of the viewport width (hence the name). So, for instance, if you wanted your text to be 4.5% of the browser's width at all times, you could use the size:

font-size: 4.5vw;

… and theoretically, that should work. Unfortunately, you'll find, it doesn't quite work as expected: there's a bug in WebKit browsers (at least) where the value for font size isn't live-updating (although it is for all other dimensions). You need to trigger a repaint in order for the font size to change, which can be done by updating the z-index property from JavaScript:

window.addEventListener('resize', function(){
    document.getElementById('myEl').style.zIndex = '1';
}, false);

This may create a little bit of choppiness, but it means you don't have to calculate any actual dimensions in JavaScript, and you don't need to used "stepped" sizes like with media queries.


The ideal way to do so is to combine between the VW font-size and @media queries. Reasons are:

1) em for itself won't rescale by window size

2) vm for itself will be too small for resolutions / screens lower than 800px.

So the right way to achieve this is:

  • Define a class - prop-text with VM=1.0 for your desired screen width
  • Add media queries to fit the font-size with your desired lower resolution grids.

For my responsive grid (which sets a 1/2 column to take 100% width below 768px width) it looks like that:

<style>
    .prop-text{font-size:1.0vw}
    @media (max-width : 768px) {
    .prop-text{font-size:2.0vw}
    }
    /*other media queries here - fit font size to smartphone resolutions */
</style>

<div class="prop-text">your text is here</div>

Set your base font size (the one you define for your body element in css) in px then everywhere in the rest of your page set font sizes relative to that one using emunit, then you can use media queries to change the font sizes of all your pages by just changing your base font, something like this:

body {
  font-size: 15px;
}
@media (max-width: 1000px) {
  body { font-size: 1.3em; }
}
@media (max-width: 500px) {
  body { font-size: 1.1; }
}