CSS ยท Chapter 27 of 44
CSS Media Queries
Media queries apply CSS rules conditionally based on screen characteristics like width, using @media (max-width: 768px) { ... } syntax.
They are the foundation of responsive design, letting you rearrange layouts, hide elements, or change font sizes at different breakpoints.
Syntax
@media (max-width: 768px) {
/* rules */
}Basic syntax
@media (max-width: 600px) { ... } applies the enclosed rules only when the viewport is 600px wide or less.
Common breakpoints
Typical breakpoints target mobile (~480px), tablet (~768px), and desktop (~1024px+), though exact values depend on your design.
Example 1 (css)
.sidebar {
width: 250px;
}
@media (max-width: 768px) {
.sidebar {
width: 100%;
}
}Output
Sidebar is 250px wide normally, but becomes full width on screens 768px or narrowerThe media query overrides the sidebar width only on small screens.
Key points
- Media queries apply CSS conditionally based on screen size.
- @media (max-width: Npx) targets screens N pixels wide or smaller.
- Media queries are core to responsive design.
- You can combine multiple conditions with 'and'.
๐ก Note: Mobile-first design typically uses min-width queries to add styles as screens grow.
