Responsive Web Design - Media Queries
Media queries are introduced in CSS3: CSS3 @media Query.
Using the @media query, you can define different styles for different media types.
Example
If the browser window is less than 500px, the background will turn light blue:
Adding Breakpoints
In previous tutorials, we used rows and columns to create web pages, which are responsive but not user-friendly on small screens.
Media queries can help us solve this problem. We can add breakpoints in the middle of our design, with different effects at different breakpoints.
Desktop Devices
Mobile Devices
Use media queries to add a breakpoint at 768px:
Example
When the screen (browser window) is less than 768px, each column's width is 100%:
Mobile-First Design
Mobile-first means prioritizing mobile design when designing for desktop and other devices.
This means we need to make some changes to our CSS.
We modify the styles for screens less than 768px, and also for screens wider than 768px. Here is a mobile-first example:
/* Mobile-first design: */
[class*="col-"] {
width: 100%;
}
@media only screen and (min-width: 768px) {
/* For desktop: */
.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}
}
Additional Breakpoints
You can add breakpoints as needed.
We can also set breakpoints for tablet and mobile devices.
Desktop Devices
Tablet Devices
Mobile Devices
Add a media query at 600px and set new styles (for screens greater than 600px but less than 768px):
Example
Note that the two sets of class styles are identical but have different names (col- and col-m-):
The above code may seem redundant, but it is necessary to automatically set different styles based on screen size.
HTML Example
For desktop devices:
The first and third sections span 3 columns. The middle section spans 6 columns.
For tablet devices:
The first section spans 3 columns, the second section spans 9 columns, and the third section spans 12 columns:
<div class="row">
<div class="col-3 col-m-3">...</div>
<div class="col-6 col-m-9">...</div>
<div class="col-3 col-m-12">...</div>
</div>
Orientation: Landscape/Portrait
Combined with CSS media queries, you can create layouts that adapt to different device orientations (landscape, portrait, etc.).
Syntax:
orientation: portrait | landscape
- portrait: Specifies that the height of the page's visible area is greater than or equal to its width.
- landscape: Anything other than the portrait value is considered landscape.
Example
If the orientation is landscape, the background will be light blue:
@media only screen and (orientation: landscape) {
body {
background-color: lightblue;
}
}