Are you tired of adjusting px values for different elements in different media queries to make your website responsive? Well, then you are at right place.
Step 1:
The first thing you should do to make your website or any website responsive is avoid using px unit. Instead of px, use rem unit. There is a simple formula to convert px to rem:
1rem = 16px
What is rem?
rem is a relative css unit. It defines unit relative to font-size of the root element. For example, root element of any html page is the html tag.
<style>
html {
/*font-size: 16px*/;
font-size: 100%
}
.header{
/* font-size: 24px*/;
/* padding: 5px */
font-size: 1.5rem;
padding: 0.312rem;
}
</style>
Here we have set the font size of root element to 100% which is equal to 16px.
Suppose the font size of the nav element is 24px. Since we are planning to avoid using px, now it has to be replaced with equivalent rem unit, which would be 24/16 rem = 1.5rem. Similarly we have to replace all the px units with rem.
As you can see, the px to rem conversion is little cumbersome. Let’s make it simple. The calculation or conversion would have been much more easier for us if somehow we can make 10px = 1rem. Sounds interesting? Here is the trick to do so.
16px = 100%
1px = 100/16 * 100 %
10px = (100/16 * 10) * 100% = 0.625 *100% = 62.5%
Now, lets modify the root element font size to be 10px i.e 62.5% and adjust rest units accordingly:
<style>
html {
/*font-size: 10px*/;
font-size: 62.5%
}
.header{
/* font-size: 24px*/;
/* padding: 5px */
font-size: 2.4rem;
padding: 0.5rem;
}
</style>
Now, easily we can convert any px to rem without using calculator! 5px is 0.5rem, 18px is 1.8rem and so on.
Step 2:
Add appropriate media queries and adjust the root element font size only. For example:
@media screen and (max-width: 768px) {
html {
font-size: 55%
}
}
That’s it. The .header
font size will automatically scale down when the media query break points are satisfied. No need to handle the .header font size explicitly in media query.
Practice this approach and your life as UI developer would be much more easier going forward. Good luck 🙂