CSS @media
queries allow you to apply styles based on device screen size, resolution, or other properties. This is essential for creating **responsive designs**.
1. Basic Syntax of Media Queries
Media queries are written using the @media
rule:
@media (condition) { /* CSS rules */ }
Example:
@media (max-width: 600px) { body { background-color: lightblue; } }
2. Common Screen Breakpoints
Here are common **CSS breakpoints** for different devices:
- Small devices (phones): max-width: 600px
- Tablets: max-width: 768px
- Laptops: max-width: 1024px
- Desktops: max-width: 1200px
3. Responsive Layout Example
Using media queries to adjust font size and layout:
body { font-size: 16px; } @media (max-width: 768px) { body { font-size: 14px; } }
4. Min-width and Max-width
Use **min-width** for progressive enhancement and **max-width** for mobile-first design.
/* Mobile-first approach */ @media (min-width: 600px) { body { background-color: lightgreen; } } /* Desktop-first approach */ @media (max-width: 600px) { body { background-color: lightcoral; } }
5. Media Queries Based on Orientation
Change styles based on **portrait** or **landscape** mode:
@media (orientation: portrait) { body { background-color: yellow; } } @media (orientation: landscape) { body { background-color: lightblue; } }
6. Targeting High-Resolution Screens
Use **media queries for Retina displays**:
@media (min-resolution: 2dppx) { body { background-image: url('high-res-image.png'); } }
7. Using Multiple Conditions
You can combine conditions using and
and or
.
/* Apply styles if width is between 600px and 900px */ @media (min-width: 600px) and (max-width: 900px) { body { background-color: orange; } }
8. CSS Media Queries for Flexbox/Grid
Adjusting layouts using **media queries with Flexbox or Grid**:
.container { display: flex; flex-direction: row; } @media (max-width: 768px) { .container { flex-direction: column; } }
9. Responsive Navigation Menu Example
Change navigation layout for smaller screens:
.nav { display: flex; justify-content: space-between; } @media (max-width: 768px) { .nav { flex-direction: column; text-align: center; } }
10. Testing Media Queries
Use **Developer Tools** in Chrome or Firefox to test media queries by resizing the window.
Conclusion
CSS Media Queries are essential for **responsive web design**. They allow your site to adapt to different screen sizes and devices.