Media Query with Bootstrap in Header

Hi coder friends!

I have this Bootstrap 3 tag in my code’s header:

<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">

I’ve tried putting that bootstrap tag before the css tag <link rel="stylesheet" href="/css/mystyles.css"> and after it. In both ways of ordering it, the following media query (in my css) doesn’t work:

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

As soon as I remove the boostrap from the header of my html, the media query does work, and the screen becomes lightblue upon resizing the window.

I checked Chrome’s Developer Tools and saw under the Computed tab, that the lightblue background color was being overriden by my css’s default background color for body.

I’ve also tried removing “only screen and”:

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

but in that case it still doesn’t work with the bootstrap in the header and still does work without the boostrap in the header.

Any ideas why this media query doesn’t work with bootstrap in the header?

My guess would be it uses a more specific selector, so its rule takes precedence. Don’t check the computed tab, but the main one, to see which rule is the one overriding yours.

Try this.

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

I’ve run into similar issues with Bootstrap’s CSS taking precedent over my CSS, and the !important rule typically will override it.

1 Like

The funny thing is that when bootstrap 3 is enabled, a less specific selector’s rule takes precedence. Both the computed and the styles tab are showing me that the body style is taking precedence over the (more specific) media query.

Are you sure media queries are any more specific? If it was also a body style, it was more likely an ordering issue.

1 Like

Aha! That solved it in a more elegant way! (Since I hear it’s better to avoid !important whenever possible.)

I added id=test to the <body> tag

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

This isn’t necessary when bootstrap 3 is disabled, but this way I can have bootstrap enabled and avoid !important. Thanks!

To summarize:
The <body> style contained in a media query outranks the <body> style, when bootstrap isn’t enabled.
When bootstrap is enabled, the main <body> style outranks the media query <body> style, even when the media query is listed later in the css.
Therefore, when bootstrap is enabled, a media query isn’t enough – the media query must be combined with specificity.