【问题标题】:Compare css selectors performance比较 CSS 选择器的性能
【发布时间】:2013-05-19 22:33:40
【问题描述】:

我有这样的代码:

HTML:

<ul class="list">
    <li class="list-item"> item 1 </li>
    <li class="list-item list-item_active"> Active item </li>    
    <li class="list-item"> item 3 </li>
    <li class="list-item"> item 4 </li>
    <li class="list-item"> item 5 </li>    
</ul>

CSS:

.list-item:nth-child(even) {
    background: #eee
}
.list-item_active {
    background: none;
}

jsfiddle 链接 - http://jsfiddle.net/Re3xV/2/

假设.list-item 没有可以设置样式的子元素。

问题:我需要.list-item_active 覆盖.list-item:nth-child(even)

我需要确定,就选择器性能而言,以下哪种解决方案是最快的:

  1. ul .list-item_active
  2. li.list-item_active
  3. .list .list-item_active
  4. .list-item.list-item_active
  5. .list-item_active:nth-child(n)
  6. .list-item:nth-child(even):not(.list-item_active)
  7. .list-item[data-state="active"] (data-state="active" 应该添加到html中)

也许我会用

.list-item_active {
    background: none !important;
}

因为它似乎根本不影响性能(而且我知道使用!important 通常是一个坏主意),但我仍然想知道,哪个选择器更快。有没有自动化的方法来进行这种比较?

【问题讨论】:

    标签: performance css css-selectors


    【解决方案1】:

    这完全与specificity有关,而不是速度。在这种情况下,.list-item:nth-child(even).list-item_active 具有更高的特异性。

    变化:

    .list-item_active { ... }
    

    收件人:

    .list-item.list-item_active { ... }
    

    http://jsfiddle.net/JamesD/Re3xV/3/

    【讨论】:

    • 列表中的所有选择器都具有更高的特异性,而不仅仅是类名。问题是 - 其中哪一个是最快的。
    • @Shtirlits:即使它们都比单个类选择器更具体,它们都有不同的具体值,而且其中一个需要您修改 HTML。这些因素会自动使您的绩效问题变得毫无意义。
    • 问题根本与特异性无关。请在写答案之前阅读问题。
    猜你喜欢
    • 2013-09-26
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 2012-09-11
    • 2012-04-28
    • 1970-01-01
    相关资源
    最近更新 更多