George Copeland
George Copeland

Reputation: 23

multiple css @media (max-width:) not working

Wondering if anyone can help me, I am trying to have multiple @media but the last @media I do overrides the other ones. so the max-width 768px overrides max-width 375..

/* Banner */
@media (max-width: 375px) {
.jumbotron {
  border-radius: 0px;
  height: 278px;
  padding-bottom: 0px;
}

.banner_title {
  font-size: 45px;
}

.banner_para {
  font-size: 15px;
}

.banner_btn {
  font-size: 15px;
}

}

    @media (max-width: 768px) {
.jumbotron {
  height: 378px;
  padding-bottom: 0px;
}

.banner_title {
  font-size: 80px;
}

.banner_para {
  font-size: 18px;
}

.banner_btn {
  font-size: 18px;
}
}

Upvotes: 0

Views: 347

Answers (2)

John_ny
John_ny

Reputation: 797

You can keep the css code in the same sequence just by adding min-width to media query as well. look at the below css code:

    /* Banner */
@media (min-width: 122px)and (max-width: 375px) {
.jumbotron {
  border-radius: 0px;
  height: 278px;
  padding-bottom: 0px;
}

.banner_title {
  font-size: 45px;
}

.banner_para {
  font-size: 15px;
}

.banner_btn {
  font-size: 15px;
}

}

@media (min-width: 376px)and(max-width: 768px) {
.jumbotron {
  height: 378px;
  padding-bottom: 0px;
}

.banner_title {
  font-size: 80px;
}

.banner_para {
  font-size: 18px;
}

.banner_btn {
  font-size: 18px;
}
}

Now you don't need to change the order of the css code. Alter the min-width size according to your requirement.

Upvotes: 0

Arno Tenkink
Arno Tenkink

Reputation: 1528

In CSS the order in which your code is executed is from the top to the bottom. It's called cascading I will place a link below for more info about it.

In your case, a maximum is set to 375px and 768px. If your viewport is 300px it's maximum is in rang of the 375px and the 768px you defined. So CSS will look at the order of which the code is defined.

Example (viewport 300px):

@media (max-width: 375px) { 
   body { background-color: red; }
}

@media (max-width: 768px) { 
   body { background-color: blue; }
}

300px is below 375px and 768px. So it passes (like an if-statement) max of 375px and 768px. The last defined body color is blue!

If you still want the same code to work, make sure the lowest value is placed last:

Example (viewport 300px):

@media (max-width: 768px) { 
   body { background-color: red; }
}

@media (max-width: 375px) { 
   body { background-color: blue; }
}

My personal recommendation is switching to min-width values instead of max. More about this: http://www.the-haystack.com/2015/12/23/choosing-between-min-and-max-width/

More about cascading: https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Cascade_and_inheritance

Upvotes: 1

Related Questions