Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I do some web app and i have some problem with font-size. How to change the font-size proportionally to the change size of the window in CSS3 or javascript?

like image 284
Misha Timofeev Avatar asked May 05 '13 14:05

Misha Timofeev


2 Answers

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.

like image 184
Matt Patenaude Avatar answered Sep 27 '22 23:09

Matt Patenaude


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>
like image 38
PalDev Avatar answered Sep 27 '22 23:09

PalDev