CSS Responsive Web Design: Media Queries Tutorial
#CSS Responsive Web Design: Media Queries Turial
Responsive web design ensures that websites look and function well on all devices, from mobile phones to desktops. One of the key tools for achieving responsive layouts is CSS Media Queries. They allow you to apply styles based on screen size, resolution, orientation, and more.
Media queries are conditional CSS rules that apply styles only when certain conditions are met. They are essential for creating layouts that adapt to different devices.
@media (max-width: 600px) {
body {
background-color: lightblue;
}
}
In the above example, the background color changes when the viewport width is 600px or less.
@media media-type and (condition) {
/* CSS rules */
}
media-type: usually screen
, print
, or all
.
condition: features like max-width
, min-width
, orientation
, etc.
Example:
@media screen and (min-width: 768px) {
.container {
width: 750px;
}
}
Start with styles for small screens, then add media queries for larger screens.
/* Mobile styles (default) */
.container {
flex-direction: column;
}
/* Tablet and up */
@media (min-width: 768px) {
.container {
flex-direction: row;
}
}
@media (max-width: 480px) {
.desktop-only {
display: none;
}
}
@media (min-width: 1024px) {
.sidebar {
float: left;
width: 25%;
}
.content {
width: 75%;
}
}
Feature | Description |
---|---|
min-width |
Triggers when viewport is at least a certain width |
max-width |
Triggers when viewport is at most a certain width |
orientation |
Checks for portrait or landscape |
resolution |
Checks device resolution (DPI) |
hover |
Detects whether hover interactions are supported |
nav ul {
display: flex;
flex-direction: row;
}
@media (max-width: 768px) {
nav ul {
flex-direction: column;
}
}
Use relative units (em
, %
) instead of fixed units (px
) where possible.
Group similar queries to avoid repetition.
Test across real devices and browser tools.
Combine with flexbox or grid for fluid layouts.
Media queries are the foundation of responsive design. By learning how to write flexible, adaptive styles, you can ensure your website looks great on any screen size. Start with a mobile-first mindset, define breakpoints wisely, and use tools like Chrome DevTools to fine-tune your layout. Embrace the responsive web—your users will thank you!