html - body 标签上的 id 相同,以提高 css 特异性

标签 html css semantics markup css-specificity

我不想使用 !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;
}

将来在所有页面的 body 标签上使用相同的 id 以获得更大的 css 特异性是否会导致问题?

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

最佳答案

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

CSS 规则最好能反射(reflect)您想要传达的内容,而不是确切的外观。示例:

<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;
}

关于html - body 标签上的 id 相同,以提高 css 特异性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33363458/

相关文章:

html - 如何在一行中设置这些 block ?

c++ - 精神提升: Invalidate parser from member function

javascript - jQuery:定位每 6 个中的第 3 个元素

css - 我如何获得像 Google zeitgeist 2011 这样的流动内容?

javascript - 如何使用正确的缩进在 html 中打印复杂的嵌套 JSON 对象?

java - 是创建一个类的一个实例更好,还是为每次出现创建一个单独的实例更好?

HTML5 语义线程注释

html - 如果 HTTP 网页向 HTTPS url 发出 ajax 请求,该帖子是否安全?

html - DIV列表链接拒绝触摸

按钮和 div 元素的 CSS 宽度不同