首页 > 解决方案 > 向 CSS 媒体查询添加重要信息

问题描述

我有一个带有内联 css 和 css 媒体查询的 html 代码在运行内联 css 时不会被媒体查询取代。我需要找到一种方法来动态地在媒体查询中的每种样式中添加那些 !important(可能与 js 一起使用)。除了以字符串形式遍历 html 内容并找到样式并添加它之外,还有其他方法可以做到这一点。我添加了一个示例代码供参考

  body {
          background-color: yellow;
        }
        @media only screen and (max-width: 600px) {
          body {
            background-color: lightblue;
          }
        }
    <body style="background-color:red;">
    </body>

标签: javascriptcssmedia-queries

解决方案


body标签中删除内联 css,因为内联 css 具有高特异性值

试试这个,在媒体查询中添加重要的内容,因为当屏幕大小改变时你需要lightblue背景颜色

body {
      background-color: yellow;
    }
    @media only screen and (max-width: 600px) {
      body {
        background-color: lightblue;
      }
    }

推荐阅读