使用新的 HTML5 元素降低 CSS 特异性

Decreased CSS Specificity with new HTML5 elements

早先将样式应用于侧边栏,我们会编写以下内容

<div id="sidebar">
<p>Some text...</p>
</div>

和相应的 CSS 将颜色设置为红色就像

#sidebar p{
color: Red;
}

这里的CSS特异性是{0,1,0,1}

在HTML5中我们有可以用作

的aside元素
<aside>
<p>Some text..</p>
</aside>

和 CSS 将颜色设置为红色

aside p{
color:Red;
}

通过使用 HTML5 元素,CSS 特异性为 {0,0,0,2}

使用 HTML5 元素改善语义。但是 HTML5 元素降低了 CSS 特异性 。如果目标浏览器支持所有 HTML5 元素,这两种方法中哪一种是合适的?

根据 MDN 文档

The specificity is a weight that is applied to a given CSS declaration based on the count of each selector type. In the case of specificity equality, the latest declaration found in the CSS is applied to the element. Specificity only applies when the same element is targeted. CSS rules that directly target an element will always take precedence over rules that an element inherits from an ancestor.

然后是标签,低于class,低于id, 还评估了外部 css link 文件优先级和内部 /in 行 css 声明。

此类信息可以参考具体浏览器(引擎)

对于 Mozilla,您可以参考此文档 https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

在你的情况下,你有一个 id css 规则(更具体)和一个标签 css 规则(次要具体)

Provided that the target browsers support all HTML5 elements which among the 2 approaches would be appropriate?

后一种使用 HTML5 元素的方法是最好的方法,但是关于规则特异性有两点需要考虑:

  1. HTML5 仅基于元素名称就可以更好地减少冲突,因为它们的数量更多,并且使用得当。考虑:

    <div class="section">words...<div class="aside"><p>an aside</p>
    

    对比

    <section>words...<aside><p>an aside</p>
    

    后者更好,因为文档的语义在标签本身内。

  2. 当你重用一个结构时,可以添加idclass属性使结构更清晰。

    <section>words...<aside><p>an aside</p>
    <section>copyright...<aside><p>year of copyright</p>
    

    对比

    <section class="article">words...<aside><p>an aside</p>
    <section class="copyright">copyright...<aside><p>year of copyright</p>
    

    此处,后者的 class 增加了上下文并减少了规则歧义。

因此,您问题的最终答案是在适当的地方智能地使用 HTML5 元素和 classes。