CSS Responsive Design

Media queries

The CSS feature that allow us to run a series of tests (screen width, resolution, height, etc.) and apply styling only when the tests pass is called media queries.

We can define as many media queries in our CSS as we want.

Syntax

@media screen and (min-width: 640px) {
.wrapper {
flex-basis: 100%;
}
}

A media query starts with the @media keyword and then a list of tests and finally the styling that should be applied if the tests pass.

In the example above, the .wrapper element stretches to take up 100% of the main axis when the screen is larger than 640px.

Code example

The example below produces a single column stacked layout of boxes for small devices and a layout with three columns for larger devices. We can use our browser's responsive design mode tool to confirm this behavior.

<div class="wrapper">
<div class="box red"></div>
<div class="box green"></div>
<div class="box blue"></div>
<div id="msg">You are using a device with a screen width of at least 768px</div>
</div>
.wrapper {
display: grid;
}
#msg {
display: hidden;
}
@media screen and (min-width: 768px) {
.wrapper {
grid-template-columns: repeat(3, 1fr);
}
#msg {
display: block;
}
}
red
green
blue

Read more on MDN

Media queries