Steve Medley
Steve Medley

Reputation: 213

Changing background color based on browser size in CSS

I can't figure out what is wrong with this code. The background color doesn't change at all, it just stays white the entire time.

<style type="text/css">
      h1 {
        position: absolute;
        text-align: center;
        width: 100%;
        font-size: 6em;
        font-family: Roboto;
        transition: all 0.5s;
      }

      @media screen and (min-width: 0px) and (max-width: 400px) {
        background-color: red;
      }
      @media screen and (min-width: 401px) and (max-width: 599px) {
        background-color: green;
      }
      @media screen and (min-width: 600px) {
        background-color: blue;
      }
    </style>

Upvotes: 0

Views: 13347

Answers (4)

Amer Kherbek
Amer Kherbek

Reputation: 1

h1 {
  position: absolute;
  text-align: center;
  width: 100%;
  transition: all 0.5s;
}

@media screen and (min-width: 0px) and (max-width: 400px) {
  body{
    background-color: red;
  }
}

@media screen and (min-width: 401px) and (max-width: 599px) {
  body{
    background-color: green;
  }
}
  
@media screen and (min-width: 600px) {
  body{
    background-color: blue;
  }
}

Upvotes: 0

Syam Pillai
Syam Pillai

Reputation: 5217

 @media screen and (min-width: 0px) and (max-width: 400px) {
   body{ background-color: red; }
 }
 @media screen and (min-width: 401px) and (max-width: 599px) {
   body{ background-color: green; }
 }
 @media screen and (min-width: 600px) {
   body{ background-color: blue; }
 }

Styles can applicable only to the body or any class onlly

Upvotes: 0

Senjuti Mahapatra
Senjuti Mahapatra

Reputation: 2590

You need to define the CSS for certain element in media query (like in this case body). Here is a demo.

Try this:

h1 {
    position: absolute;
    text-align: center;
    width: 100%;
    font-size: 6em;
    font-family: Roboto;
    transition: all 0.5s;
  }

  @media screen and (min-width: 0px) and (max-width: 400px) {
    body{
      background-color: red;
    }
  }
  @media screen and (min-width: 401px) and (max-width: 599px) {
    body{
      background-color: green;
    }
  }
  @media screen and (min-width: 600px) {
    body{
      background-color: blue;
    }
  }

Upvotes: 1

Gilad Artzi
Gilad Artzi

Reputation: 3084

Try:

@media screen and (min-width: 0px) and (max-width: 400px) {
    body { background-color: red; }
}
@media screen and (min-width: 401px) and (max-width: 599px) {
    body { background-color: green; }
}
@media screen and (min-width: 600px) {
    body { background-color: blue; }
}

The background-color property is now assigned to the body

Upvotes: 7

Related Questions