Vikas Kumar Vikas Kumar - 5 months ago 18
CSS Question

Why isn't media query on max-width working?

I want to control the size of my logo using media query.

The original

width
of my logo is
210px
.

I want it to be
166px
when the screen
width
is greater than
56.865em
and same when it is less than this
width
, i.e., for mobile site.

I have written following code for this:

@media only screen and (min-width: 56.875em){
.site-branding img{
max-width: 166px;
}
}

@media only screen and (max-width: 56.875em){
.site-branding img {
max-width: 166px !important;
}
}


Only the first code block is working. Why isn't second working? (When the screen width is decreased, the
width
of logo becomes
210px
again).

Is there any rule that you can't use both
min
and
max
media-queries to control same element?

Answer

The max-width rule won't work because it is overridden by the min-width since both have same value.

an easy approach, instead of doing 2 media queries is simply setting the logo's width in the general CSS and then apply a media query:

  • via non-mobile approach using the max-width

    or

  • via the mobile first approach using min-width

Option with max-width

.logo img {
  width: 210px
}
@media (max-width: 56.865em) {
  .logo img {
    width: 166px
  }
}
<div class="logo">
  <img src="//lorempixel.com/300/300">
</div>

Option with min-width

.logo img {
  width: 166px
}
@media (min-width: 56.865em) {
  .logo img {
    width: 210px
  }
}
<div class="logo">
  <img src="//lorempixel.com/300/300">
</div>


UPDATE

First, I want the logo size 166px all the time.

So if you want after all is to have the logo's width at 166px all the time, meaning you want to change the current 210px to 166px

Then you don't need media queries. Assuming you are changing a custom CSS file and you can't/want to change the Base CSS file (which contains the width:210px) all you need is to be more specific.

See more about CSS specificity.

/* emulating Base CSS */

.logo img {
  width: 210px
}
/*being more specific */
.header .logo img {
  width: 166px
}
<div class="header">
  <div class="logo">
    <img src="//lorempixel.com/300/300">
  </div>
</div>