This content originally appeared on DEV Community and was authored by Josh Lee
Hey, Josh here again. Lately, I’ve been showing you how to build projects with Ruby on Rails and React.js. Today, I’m going to show you something a little bit different – how to easily make your website responsive.
If you’ve written any CSS for responsive websites, then you know how much of a pain it can be to write media queries. This responsive technique involves only changing your font-size for each media query.
It’s all about using the ‘rem’ unit instead of using pixels. You might be used to writing something like this:
.my-class {
margin-top: 16px;
}
Instead of using the ‘px’ unit, you should be using the ‘rem’ unit. But how does the ‘rem’ unit work?
‘Rem’ stands for root em and it’s a dynamic value based on the root font-size. The browser default font-size is 16px. That means 1 rem == 16px. In our above example, we can use the following:
.my-class {
margin-top: 1rem;
}
But that doesn’t really change anything right now. We have the same margin at the top of our class. So why did we do this?
Easy, now, in your media queries, you can change your font-size and this will change everything that uses the ‘rem’ unit.
@media only screen and (max-width: 600px) {
html {
font-size: 80%;
}
}
This makes your font 80% of the root em, currently at 16px. That means on this media query, your font-size becomes 12.8px. And all of the other CSS you’ve written will now be based on this 12.8px value.
By making this one change – the font-size of the HTML file – you change everything else that uses the rem units.
You should immediately see how powerful this is. Instead of writing a ton of CSS in your media queries, all you have to do is adjust your font-size. Sure, you might have to add some more CSS, but this does most of the heavy lifting.
I should also note, instead of basing everything off the 16px value (the browser's default), you can just set your font-size in your html element without the media queries.
html {
font-size: 62.5%;
}
This content originally appeared on DEV Community and was authored by Josh Lee
Josh Lee | Sciencx (2021-06-02T07:47:33+00:00) A Simple CSS Trick to Instantly Make a Site Responsive Without Having a Ton of Code in Your Media Queries. Retrieved from https://www.scien.cx/2021/06/02/a-simple-css-trick-to-instantly-make-a-site-responsive-without-having-a-ton-of-code-in-your-media-queries/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.