【问题标题】:Same id on body tag for greater css specificity身体标签上的相同 id 以获得更大的 css 特异性
【发布时间】:2023-03-27 05:28:02
【问题描述】:

我不想使用 !important 或为每个可以使用辅助类处理的案例编写新规则。比如我想做;

HTML

<body id="sameId">
    <div class="wrapper">
        <div class="article text-center text-bold">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>

        <div class="article">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>

        <div class="article">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>

        <div class="article">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>

        <div class="article">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>

        <div class="article">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
    </div>
</body>

CSS

/* Helper Classes */
#sameId .text-center {
    text-align:center;
}

#sameId  .text-bold {
  font-weight: bold;
}


/* Article Styles */
.wrapper .article {
    padding: 10px;
    margin-bottom: 20px;
    border: 1px solid #ddd;
    text-align:left;
    font-weight: normal;
}

在所有页面的正文标签上使用相同的 id 以提高 css 特异性是否会导致将来出现问题?

https://jsbin.com/tamaxetuse/1/edit?html,css,output

【问题讨论】:

  • 您在.wrapper .article 中显式设置text-alignfont-weight 是否有原因?如果它们没有被 CSS 前面的其他规则覆盖,您可以简单地 omit them

标签: html css semantics markup css-specificity


【解决方案1】:

如果你正在使用这样的辅助类,你也可以在其中使用!important 或直接在 HTML 标记中编写样式。它们只是内联样式的替代品,因此您并没有真正将内容与样式分开。

CSS 规则应该更好地反映您想要传达的内容,而不是确切的外观。示例:

<body>
    <div class="wrapper">
        <div class="article first-article">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
    </div>
</body>

CSS:

/* Article Styles */
.wrapper .article {
    padding: 5px;
    border: 1px solid #ddd;
    text-align:left;
    font-weight: normal;
}

.wrapper .article.first-article {
    text-align:center;
    font-weight: bold;
}

【讨论】:

  • @insertusernamehere:您正在考虑列表中第一项具有不同样式的特定情况。但该示例旨在展示如何根据信息的各个方面而不是视觉外观来命名规则。
猜你喜欢
  • 2020-07-20
  • 2011-04-24
  • 1970-01-01
  • 2012-07-22
  • 2017-02-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-01
  • 1970-01-01
相关资源
最近更新 更多