CSS Media Queries

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 */
}

Try It Now

Example:

@media (max-width: 600px) {
    body {
        background-color: lightblue;
    }
}

Try It Now

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;
    }
}

Try It Now

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;
    }
}

Try It Now

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;
    }
}

Try It Now

6. Targeting High-Resolution Screens

Use **media queries for Retina displays**:

@media (min-resolution: 2dppx) {
    body {
        background-image: url('high-res-image.png');
    }
}

Try It Now

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;
    }
}

Try It Now

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;
    }
}

Try It Now

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;
    }
}

Try It Now

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.