Mastering the Viewport: An Intro to CSS Media Queries
When we create a website, we want it to look good on every device, from a large desktop monitor to a small smartphone screen. This is the core principle of responsive web design, and the key tool for achieving it is the CSS media query.
A media query allows us to apply specific styles only when certain conditions are met, such as the screen width. This means we can serve a different, optimized layout to a user on a mobile device without building a completely separate website. It's how a website can "respond" to its environment.
Let's look at a simple example. We'll start with a basic layout that works on desktop, and then use a media query to change it for mobile.
Our Default (Desktop) Layout
/* Styles for screens larger than 768px (the default) */
.container {
display: flex;
justify-content: space-between;
padding: 20px;
background-color: #f0f0f0;
}
.box {
width: 30%;
padding: 20px;
background-color: #007bff;
color: white;
text-align: center;
border-radius: 8px;
}
This CSS creates a horizontal row of three boxes, perfect for a desktop screen.
The Mobile View: Using a Media Query
Now, let's use a media query to stack these boxes vertically when the screen is too narrow to hold them side-by-side. We'll set a "breakpoint" at 768 pixels, a common width for tablets.
@media (max-width: 768px) {
.container {
flex-direction: column; /* Stack the boxes vertically */
align-items: center; /* Center the stacked boxes */
}
.box {
width: 90%; /* Make the boxes wider to fill the screen */
margin-bottom: 15px; /* Add some space between them */
}
}
This code tells the browser: "When the screen is 768 pixels wide or less, apply these new styles." The flex-direction: column
property is the magic that changes our layout from a row to a stack, and we adjust the box width and margin to make it look great on a phone.
By using media queries, you can ensure your web applications are not only functional but also provide a great user experience, no matter how a user is viewing them. It's a fundamental step in building modern, accessible websites.
Top comments (0)