CSS 不使用 !important 并遵循 DRY 原则

CSS without using !important and follow DRY principal

我不喜欢在 CSS 上使用 !important。但不幸的是,我有一种情况不能忽视它。你知道如何克服这种情况吗?

例如我需要在许多 Ionic 页面上使用它。

.font-bold {
    font-weight: bold;
}

如果我在每一页上都使用它,那么我就不需要 !important。但是上面那种代码违反了DRY原则。

要关注DRY我可以这样做:

global.scss

 .font-bold {
        font-weight: bold !important;
    } 

那么如何在不使用 Ionic 5 应用程序 !important 的情况下遵循 DRY?

使用 !important1 没有任何问题,但您始终可以尝试增加选择器的特异性以使其始终获胜。

一个想法是考虑与 :not() 选择器组合的具有最高特异性的 ID。只需确保使用永远不会被使用的随机 ID:

.font-bold:not(#randomID) {
  font-weight: bold;
}

.box p {
  font-weight: 200;
}
<div class="box">
  <p>some text here</p>

</div>

<div class="box">
  <p class="font-bold">some text here</p>
</div>

此处有更多详细信息:


1:Boostrap 使用大约 1000 !important (https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css)

Stack Overflow 也使用大约 2970 !important (https://whosebug.com/Content/Shared/stacks.css)