CSS Media Queries
Media queries allow you to apply different CSS rules depending on the device's screen size, orientation, resolution, and more. Theyβre the foundation of responsive web design.
1. Basic Syntax
A simple media query that targets devices with a max width of 600px:
@media (max-width: 600px) {
body {
background-color: lightgray;
}
}
2. Common Use Cases
- Adjust layout for phones, tablets, and desktops
- Hide/show elements based on screen size
- Change font sizes or paddings
3. Common Breakpoints
/* Smartphones */
@media (max-width: 480px) { ... }
/* Tablets */
@media (min-width: 481px) and (max-width: 768px) { ... }
/* Small Laptops */
@media (min-width: 769px) and (max-width: 1024px) { ... }
/* Desktops */
@media (min-width: 1025px) { ... }
4. Orientation Queries
Apply styles based on screen orientation:
@media (orientation: landscape) {
.gallery {
flex-direction: row;
}
}
5. Combining Conditions
You can combine multiple media features:
@media (min-width: 768px) and (orientation: portrait) {
.sidebar {
display: none;
}
}
6. Responsive Design Tips
- Start with a mobile-first approach using
min-width
. - Use relative units like
em
,%
, orrem
. - Test on real devices and various screen sizes.
Conclusion
Media queries are a crucial part of modern CSS, allowing your website to adapt to any device or screen size. Mastering them is essential for building fully responsive, mobile-friendly websites.