Kanchan Rai Kanchan Rai - 6 months ago 10
HTML Question

Media Queries, which one is the better way and why?

I've been writing Media Queries, after all of my normal CSS styles (desktop and laptop devices). But, recently, looking at some examples and bootstraps CSS files, I notice media queries are directly followed after the css is written. This example will better illustrate my question,

.content {
padding-top: 20px;
padding-bottom: 40px;
font-size: 1rem;
}
.something{
background: red;
padding:20px;
width:800px;
}
// The Media Queries after I write all normal CSS
@media only screen and (max-width: 768px) {
.content{
padding:10p;
//some style for mobile
}
.something{
width:100%;
//some style for mobile
}
}


Or

.content {
padding-top: 20px;
padding-bottom: 40px;
font-size: 1rem;
}
// Media Query Directly After the CSS
@media only screen and (max-width: 768px) {
.content{
padding:10p;
//some style for mobile
}
}
.something{
background: red;
padding:20px;
width:800px;
}
// Media Query Directly After the CSS
@media only screen and (max-width: 768px) {
.something{
width:100%;
//some style for mobile
}
}


So, I'm curious, which is the correct way or the better way?

I've been doing the first way, as I don't have to repeat the media queries "@media only screen and (max-width: ..px)" everytime.

Thanks

Answer

Clearly one would prefer to group the media query versions of the CSS rules together with the non-media query versions, so they can be managed together. For example, if I write separate CSS for each component, I would usually want both media query versions and non-media query versions of the rules for that component to be in the file for that component. When I add and modify rules, I would prefer to do that in one place, rather than two or more.

If it bothers you that you have to write the media query again and again, which is a valid concern from the standpoint of maintaining your code when changing breakpoints, consider using a preprocessor such as postCSS which allows you to define aliases for media queries. For instance, this plugin would allow you to write

@custom-media --small-viewport (max-width: 30em);

@media (--small-viewport) {
  /* styles for small viewport */
}
Comments