首页 > 解决方案 > 为什么这个媒体查询不切换显示属性?

问题描述

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <style>
      body {
      color: white;
      background-color: #1E1B1B;
      border-color: grey;
      }
      .navbar {
      height: 50px;
      border-bottom: 2px solid grey;
      margin-bottom: 10px;
      }
      button.nav-btn, button.drop-down-toggle {
      float:right;
      background-color: transparent;
      border: 1px solid grey;
      color: white;
      padding: 5px 12px;
      font-size: 30px;
      cursor: pointer;
      }

      @media (max-width: 500px) {
      button.drop-down-toggle {
          display: none;
          border: 1px solid red;
      }
      }
    </style>

    <script>

    </script>
  </head>

  <body>
    <div class="navbar">
      <button class="drop-down-toggle" style="float:left; display:block;"><i class="fa fa-bars"></i></button>
      <button class="nav-btn"><i class="fa fa-user-circle-o"></i></button>
    </div>
  </body>
</html>

如果您运行代码并将屏幕尺寸降低到 500 像素以下,则边框会按预期变为红色,但实际上应该是。

标签: htmlcss

解决方案


内联样式在所有 CSS 中具有最高优先级,而您的按钮确实具有

style= "display: block"

我建议避免使用内联 css,另一种选择是!important在媒体查询中使用

@media (max-width: 500px) {
      button.drop-down-toggle {
      display: none !important;
      border: 1px solid red;
}

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <style>
      body {
      color: white;
      background-color: #1E1B1B;
      border-color: grey;
      }
      .navbar {
      height: 50px;
      border-bottom: 2px solid grey;
      margin-bottom: 10px;
      }
      button.nav-btn, button.drop-down-toggle {
      float:right;
      background-color: transparent;
      border: 1px solid grey;
      color: white;
      padding: 5px 12px;
      font-size: 30px;
      cursor: pointer;
      }

      @media (max-width: 500px) {
      button.drop-down-toggle {
          display: none;
          border: 1px solid red;
      }
      }
    </style>

    <script>

    </script>
  </head>

  <body>
    <div class="navbar">
      <button class="drop-down-toggle" style="float:left;"><i class="fa fa-bars"></i></button>
      <button class="nav-btn"><i class="fa fa-user-circle-o"></i></button>
    </div>
  </body>
</html>


推荐阅读