Search code examples
htmlcssbrowsermobilestylesheet

How to properly use media query to change a style based on display width?


I have a style which I want to be different in mobile devices. The style is in a stylesheet containing a lot of styles.

The style is like this:

.header_wrapper{
     background-image:bla bla bla;
}

I want the above style to have NO background image when beeing shown in mobile devices with width smaller than say 480px? (just a guess of the width, but feel free to suggest a good width):

.header_wrapper{
     background-image:none;
}

Is it possible to do all this from one stylesheet? Or do I need to copy the entire stylesheet (there are lots of styles) just to change the one style, and then add the stylesheet to the website?

How about order of precedence?


Solution

  • It is possible to do this all from one stylesheet using media queries.

    The css would be something like:

    @media screen and (max-device-width: 480px) {
        .header_wrapper{
             background-image:none;
        }
    }
    

    This should be placed at the end of the stylesheet to ensure it overrides the previous style.

    You can also use media queries to link to a separate stylesheet if there are many styles to override.

    <link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="mobile.css" />