【问题标题】:Why do I have to use the !important in this case? [duplicate]为什么在这种情况下我必须使用 !important ? [复制]
【发布时间】:2020-08-19 15:45:58
【问题描述】:

这是 CSS:

.parent div {
height: 25px;
width: 25%;
}

.child {
width: 50% !important;
height: 50px !important;
}

这是 HTML:

<body>
<div class="parent">
    <div class="child">
        <p>CHILD</p>
    </div>
</div>
</body>

浏览器从上到下执行 CSS。我阅读了有关 CSS 层次结构的信息,据此,当我指定应该应用其代码的类时。无论如何,它应用 .parent div 代码.. 我哪里错了?

【问题讨论】:

标签: html css


【解决方案1】:

更具体地使用您的 css 并删除您所有的 !importants:

.parent div.child {
    width: 50%;
    height: 50px;
}

应该没问题

【讨论】:

    【解决方案2】:

    您正在使用.parent div,这意味着它将对嵌套在.parent 类中的所有 div 应用样式

    <div class="parent">
      <p>This will not be affected as it's not div tag</p>
      <span>This will not be affected as it's not div tag</span>
      <div>This will be affected</div>
      <div class="child">This affects also</div>
    </div>
    

    这就是为什么它只应用.child 类的样式和!important,因为你必须覆盖子类。

    以下是您可以使用的一些变体:

    .parent {
      height: 25px;
      width: 25%;
    }
    
    .child {
      width: 50%;
      height: 50px;
    }
    
    .parent {
      height: 25px;
      width: 25%;
    }
    
    .parent .child {
      width: 50%;
      height: 50px;
    }
    

    【讨论】:

      【解决方案3】:

      !important 用于覆盖任何其他可能也适用于应用 !important 的元素的 CSS 规则。这可以确保不会应用影响相同属性的其他 CSS 规则,从而确保样式标记 !important 是适用的。

      正如其他人所说,您的问题的原因源于您对 css 选择器和组合器的应用

      更多阅读:https://www.w3schools.com/css/css_combinators.asp

      【讨论】:

        【解决方案4】:

        .parent div 的特异性高于.child

        但是,如果您使用.parent .child 而不是仅使用.child,那么它的特异性比.parent div 更高,因此您不需要添加!important,如下所示:

        .parent .child {
           width: 50%;
           height: 50px;
        }
        

        关于 CSS 特性的一些有用的读物​​:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-11-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-02
          • 2017-03-05
          • 1970-01-01
          相关资源
          最近更新 更多