How To Add Multiple Media Queries In Css

In today’s world of responsive design, making sure your website looks great on a variety of devices is essential. One of the most powerful tools to achieve this is media queries in CSS. Media queries allow you to apply different styles based on the properties of a user’s device, such as screen size, resolution, and orientation. In this blog post, we’ll discuss how to add multiple media queries to your CSS to create a truly responsive design.

Understanding Media Queries

The basic structure of a media query consists of a @media rule, followed by a set of conditions and a block of CSS rules. The CSS rules inside the media query will only be applied if the conditions are met. Here’s a simple example:

    @media screen and (min-width: 768px) {
        /* CSS rules go here */
    }
    

In this example, the CSS rules inside the media query will only be applied if the user’s device has a screen width of at least 768 pixels.

Adding Multiple Media Queries

To add multiple media queries, simply create additional @media rules with their own conditions and CSS rules. Let’s say we want to apply different styles for small, medium, and large devices. We can accomplish this with the following code:

    /* Small devices (mobile) */
    @media screen and (max-width: 767px) {
        /* CSS rules for small devices go here */
    }

    /* Medium devices (tablets) */
    @media screen and (min-width: 768px) and (max-width: 1023px) {
        /* CSS rules for medium devices go here */
    }

    /* Large devices (desktops) */
    @media screen and (min-width: 1024px) {
        /* CSS rules for large devices go here */
    }
    

In this example, we’ve created three media queries targeting small, medium, and large devices. The CSS rules inside each media query will only be applied if the user’s device matches the specified conditions.

Combining Media Queries

Sometimes, you may want to apply a set of CSS rules if either one of two (or more) conditions are met. In this case, you can use the , (comma) to combine multiple media queries into a single rule. For example, suppose you want to apply a specific style to both portrait and landscape orientations on mobile devices. You can do this with the following code:

    @media screen and (max-width: 767px) and (orientation: portrait),
           screen and (max-width: 767px) and (orientation: landscape) {
        /* CSS rules go here */
    }
    

In this example, the CSS rules inside the media query will be applied if the user’s device is a mobile device in either portrait or landscape orientation.

Conclusion

Adding multiple media queries in CSS is a powerful way to create responsive designs that adapt to various devices and conditions. By understanding how to use media queries effectively, you can ensure that your website looks great on any screen size, resolution, or orientation. Happy coding!