Responsive Design with CSS3 Media Queries
๐ฑ CSS3 Media Queries for Responsive Design
Media queries are a cornerstone of responsive web design, enabling styles to adapt to various device characteristics.
๐งช Basic Media Query Example
@media (max-width: 768px) {
body {
background-color: lightgray;
}
}
โ Applies styles only when the screen width is 768px or less.
๐ Common Media Query Features
min-width
/max-width
: screen sizeorientation
: portrait or landscaperesolution
: pixel density
๐ Combine with Flexible Units
Use %
, vw
, vh
, em
, and rem
for scalable layouts:
.container {
width: 90vw;
padding: 2em;
}
๐งฑ Example: Responsive Layout Shift
/* Desktop */
@media (min-width: 1024px) {
.content {
display: grid;
grid-template-columns: 1fr 1fr;
}
}
/* Mobile */
@media (max-width: 768px) {
.content {
display: block;
}
}
โ Switches from two columns to a single column on smaller screens.
๐ฏ Benefits of Responsive Design
- ๐ Improves accessibility
- ๐ค Enhances user experience
- ๐ Boosts SEO performance
- ๐ฑ Optimizes content for all device sizes
Mastering media queries ensures your websites are flexible, accessible, and device-friendly.