If you’re a web developer or designer, you’ve probably heard of responsive design.
It’s the practice of designing websites that can adapt to different screen sizes, from desktops to mobile devices.
And one of the key tools for achieving responsive design is media queries.
Media queries are CSS rules that allow you to apply different styles to different devices based on their screen size or other characteristics.
For example, you might want to display a three-column layout on a desktop, but switch to a one-column layout on a mobile device.
Learning media queries is essential for anyone who wants to create modern, responsive websites that work well on all devices.
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
Let’s say you’re designing a website for a restaurant.
You want the website to display a three-column layout on desktops, a two-column layout on tablets, and a one-column layout on mobile devices.
Here’s how you might use media queries to achieve this:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
.container {
display: flex;
justify-content: space-between;
}
.column {
width: 30%;
}
@media only screen and (max-width: 768px) {
.container {
flex-wrap: wrap;
}
.column {
width: 45%;
margin: 0 2.5%;
}
}
@media only screen and (max-width: 480px) {
.container {
flex-direction: column;
}
.column {
width: 100%;
margin: 0;
}
}