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).
This section shows mobile-first approach template.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.class-name {
7
/* some styles for mobile device screen */
8
}
9
10
/* additionally min-height: [screen_height]px can be used */
11
@media (min-width: [screen_width]px) {
12
13
/* overridden some styles here e.g. small tablet */
14
15
.class-name {
16
/* place for styles... */
17
}
18
}
19
20
/* additionally min-height: [bigger_screen_width]px can be used */
21
@media (min-width: [bigger_screen_width]px) {
22
23
/* overridden some styles here e.g. normal desktop screen */
24
25
.class-name {
26
/* place for styles... */
27
}
28
}
29
30
/* additionally min-height: [much_more_bigger_screen_width]px can be used */
31
@media (min-width: [much_more_bigger_screen_width]px) {
32
33
/* overridden some styles e.g. big desktop screen */
34
35
.class-name {
36
/* place for styles... */
37
}
38
}
39
40
/* other media cases... */
41
42
</style>
43
</head>
44
<body>
45
<div class="class-name">
46
<!-- Template here... -->
47
<div>
48
</body>
49
</html>
In this section, you can see practical example for mobile-first approach.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
/* for mobile */
7
8
.content {
9
padding: 10px;
10
border: 5px solid orange;
11
background: red;
12
}
13
14
.content button {
15
border: 1px solid gray;
16
}
17
18
/* END: for mobile */
19
20
@media (min-width: 600px) {
21
/* for bigger screen */
22
23
.content {
24
background: blue; /* overridden for tablet */
25
}
26
27
.content button {
28
border: 3px solid red;
29
}
30
}
31
32
@media (min-width: 1024px) {
33
/* for much more bigger screen */
34
35
.content {
36
background: gray; /* overridden for desktop */
37
}
38
39
.content button {
40
border: 6px solid blue;
41
}
42
}
43
44
</style>
45
</head>
46
<body>
47
<div class="content">
48
Resize window to see effect...
49
<br />
50
<button>Click me!</button>
51
</div>
52
</body>
53
</html>