What is a Media Query?
Media query is a CSS technique introduced in CSS3.
It uses the @media rule to include a block of CSS properties only if a certain condition is true.
If the browser window is smaller than 500px, the background color will change to lightblue:
Add a Breakpoint
Earlier in this tutorial we made a web page with rows and columns, and it was responsive, but it did not look good on a small screen.
Media queries can help with that. We can add a breakpoint where certain parts of the design will behave differently on each side of the breakpoint.
Use a media query to add a breakpoint at 768px:
When the screen (browser window) gets smaller than 768px, each column should have a width of 100%:
Always Design for Mobile First
Mobile First means designing for mobile before designing for desktop or any other device (This will make the page display faster on smaller devices).
This means that we must make some changes in our CSS.
Instead of changing styles when the width gets smaller than 768px, we should change the design when the width gets larger than 768px. This will make our design Mobile First:
You can add as many breakpoints as you like.
We will also insert a breakpoint between tablets and mobile phones.
We do this by adding one more media query (at 600px), and a set of new classes for devices larger than 600px (but smaller than 768px):
Note that the two sets of classes are almost identical, the only difference is the name (col- and col-m-):
It might seem odd that we have two sets of identical classes, but it gives us the opportunity in HTML, to decide what will happen with the columns at each breakpoint:
The first and the third section will both span 3 columns each. The middle section will span 6 columns.
The first section will span 3 columns, the second will span 9, and the third section will be displayed below the first two sections, and it will span 12 columns:
Orientation: Portrait / Landscape
Media queries can also be used to change layout of a page depending on the orientation of the browser.
You can have a set of CSS properties that will only apply when the browser window is wider than its height, a so called "Landscape" orientation:
The web page will have a lightblue background if the orientation is in landscape mode: