【问题标题】:CSS, changing already specified property within media query not working [duplicate]CSS,在媒体查询中更改已指定的属性不起作用[重复]
【发布时间】:2022-08-08 13:45:02
【问题描述】:

我目前正在为大学项目创建一个网站。因此,我想根据屏幕尺寸(针对移动用户)更改视图。

因此,我想更改一些我已经在相关类中指定的属性,但似乎这是不可能的。

为了说明问题,我创建了这两个按钮。 Button 1 的颜色由 background-color: blue 指定,如果尺寸小于 600 像素,则将其更改为红色,而 Button 2 的颜色未指定。

当您现在更改 Screen-size 时,您会看到只有 Button 2 的颜色会被更改。

所以我的问题是:是否可以更改已经指定的属性,如果可以,如何更改?

先感谢您!

@media screen and (max-width: 600px) {
   .button_one {
      background-color: red;
   }
   
   .button_two {
      background-color: green;
   }
}

.button_one {
  background-color: blue;
}
</head>
  <body>

    <div>
      <button class=\"button_one\"> Button 1 </button>
      <button class=\"button_two\"> Button 2 </button>
    </div>

  </body>
</html>

    标签: html css


    【解决方案1】:

    蓝色背景在这里获胜只是因为它出现在样式表的后面。媒体查询不影响特异性。为此,您应该更改媒体查询的位置,如下所示:

    .button_one {
      background-color: blue;
    }
    
    @media screen and (max-width: 600px) {
       .button_one {
          background-color: red;
       }
       
       .button_two {
          background-color: green;
       }
    }
    <div>
          <button class="button_one"> Button 1 </button>
          <button class="button_two"> Button 2 </button>
    </div>

    【讨论】:

    • 啊,就这么简单……太棒了!非常感谢! :)
    • 我从没想过这种行为。我正在做一些研究,发现媒体查询中的类必须具有更高的特异性才能被覆盖。所以为了改变颜色,我使用了button.button_one { background-color: red; }。有效
    【解决方案2】:

    您可以使用 CSS 的 !important 属性,如下所示:

    @media screen and (max-width: 600px) {
      .button_one {
       background-color: red !important;
    }
    
      .button_two {
          background-color: green !important;
      }
    }
    
     .button_one {
     background-color: blue;
    }
    

    当屏幕尺寸改变时,这将覆盖默认值。

    【讨论】:

      猜你喜欢
      • 2013-08-14
      • 2011-09-25
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      相关资源
      最近更新 更多