Using CSS media queries for responsive layout
In this article, we are going to create a simple web site that can fit into different screen size by using CSS media queries.
We start from the above project and duplicate the columns twice.
Syntax
@media screen and (max-width: 480px) {
}
We will write the CSS rules within the curly braces. We will apply those CSS rules to all screens with maximum width of 480px.
It will apply these rules if the screen is less than 480px and ignore these rules if larger than 480 rules.
Making CSS rules
These CSS rules are only going to be targeted towards screens which
have a maximum width of 700 pixels.
If the viewport is bigger than 700 pixels it is going to ignore these rules.
@media screen and (max-width:700px) {section{background-color: aqua;}}
The background color change to aqua when the screen size is less than 700px.
More CSS rules
We usually do more positional things to make the web fit better.
@media screen and (max-width:700px) {section{width:46%;}}@media screen and (max-width:480px) {section{width:96%;}}
When the screen size is less than 700px , we will set the width to 46%, with padding and margin (4%) which add up to 50%, it will display two columns only.
When the screen size is less than 480px, we will set the width to 96%, with 4% padding and margin, which mean each column will take up 100% width of the screen, so it just display one column only.