让我们覆盖自己的CSS

时间:2019-05-01 10:51:53

标签: css sass

是否有可能创建一种样式,如果不使用!important而让它有其他任何值,则可以覆盖其自身? 我不能使用!important,因为它会破坏动画。

.p-20{
  padding: 20px;
}

.panel{
  .heading{
    //this would be the default value and would let himself be override
    padding: 10px;
  }
}
<div class="panel">
   <div class="heading p-20">
      My padding is 10px instead of 20px...
   </div>
</div>

3 个答案:

答案 0 :(得分:2)

您可以创建一种新样式,并赋予样式相同的特异性,然后在要覆盖的样式之后应用它。

<div class="panel">
   <div class="heading p-20 new-class">
      My padding is 10px instead of 20px...
   </div>
</div>

css

.panel{
  .heading{
    padding: 10px;
  }
  .new-class{
    padding: 20px;
  }
}

答案 1 :(得分:0)

@LGSon在评论中以以下方式回答了我的问题:  “基本上有两种方式,specificity!important,如果它们相等,则CSS中的最后一条规则将适用”。 这意味着无论如何都将样式声明为默认样式。 就像他说的那样,必须使用specificity!important完成,但是!important应该永远是最后的资源。

答案 2 :(得分:0)

这听起来像CSS变量的工作,而您不必关心特异性:

.p-20 {
  --p: 20px;
  padding:20px; /*we keep this for the element without variable*/
}

.panel .heading {
  padding: var(--p, 10px); /* 10px will be the default value if --p is not set*/
  background:red;
}
<div class="panel">
  <div class="heading">
    My padding is 10px
  </div>
</div>
<div class="panel">
  <div class="heading p-20">
    My padding is 20px
  </div>
</div>

<div class="panel">
  <div class="p-20">
    My padding is 20px
  </div>
</div>

相关问题