EN
CSS - How would you use media queries in a mobile-first approach?
14
points
This post was created to answer for the question:
How would you use media queries in a mobile-first approach?
The answer:
Starting from defining styles for mobile devices and later by overriding styles with
@media
from smaller sizes of screen to bigger (min-width
/min-height
andmax-width
/max-height
help to select screen size).
The main concept
This section shows mobile-first approach template.
<!doctype html>
<html>
<head>
<style>
.class-name {
/* some styles for mobile device screen */
}
/* additionally min-height: [screen_height]px can be used */
@media (min-width: [screen_width]px) {
/* overridden some styles here e.g. small tablet */
.class-name {
/* place for styles... */
}
}
/* additionally min-height: [bigger_screen_width]px can be used */
@media (min-width: [bigger_screen_width]px) {
/* overridden some styles here e.g. normal desktop screen */
.class-name {
/* place for styles... */
}
}
/* additionally min-height: [much_more_bigger_screen_width]px can be used */
@media (min-width: [much_more_bigger_screen_width]px) {
/* overridden some styles e.g. big desktop screen */
.class-name {
/* place for styles... */
}
}
/* other media cases... */
</style>
</head>
<body>
<div class="class-name">
<!-- Template here... -->
<div>
</body>
</html>
Practical example
In this section, you can see practical example for mobile-first approach.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
/* for mobile */
.content {
padding: 10px;
border: 5px solid orange;
background: red;
}
.content button {
border: 1px solid gray;
}
/* END: for mobile */
@media (min-width: 600px) {
/* for bigger screen */
.content {
background: blue; /* overridden for tablet */
}
.content button {
border: 3px solid red;
}
}
@media (min-width: 1024px) {
/* for much more bigger screen */
.content {
background: gray; /* overridden for desktop */
}
.content button {
border: 6px solid blue;
}
}
</style>
</head>
<body>
<div class="content">
Resize window to see effect...
<br />
<button>Click me!</button>
</div>
</body>
</html>