简体   繁体   English

在 CSS 中根据浏览器大小更改背景颜色

[英]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>

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 现在将background-color属性分配给body

You need to define the CSS for certain element in media query (like in this case body ). 您需要为media query某些元素定义CSS (如本例中的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;
    }
  }
 @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 样式仅适用于身体或任何类别

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; } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM