【问题标题】:Which of these pieces of CSS is more efficient for achieving the desired result?这些 CSS 中哪一个更有效地实现了预期的结果?
【发布时间】:2015-05-03 00:19:56
【问题描述】:

以下哪项将花费更少的时间被浏览器读取?还有什么我可以做的额外的微优化(当然,除了消除空白)?

选项 1:

        ol.red-numbers > li:before { color: #A71930; padding-right: 5px; }
        ol.red-numbers > li:nth-of-type(1):before { content: "1"; }
        ol.red-numbers > li:nth-of-type(2):before { content: "2"; }
        ol.red-numbers > li:nth-of-type(3):before { content: "3"; }

选项 2:

        ol.red-numbers > li:nth-of-type(1):before { color: #A71930; padding-right: 5px; content: "1"; }
        ol.red-numbers > li:nth-of-type(2):before { color: #A71930; padding-right: 5px; content: "2"; }
        ol.red-numbers > li:nth-of-type(3):before { color: #A71930; padding-right: 5px; content: "3"; }

【问题讨论】:

  • “还有我可以做的其他微优化吗?”至少你知道你在做什么,但是……你没有更好的事情要做吗?
  • @BoltClock 一位智者曾经说过,“微优化是最大的好处。”
  • 我从未将一个列表项视为另一个列表项的直接子项,如果这是有效标记,我会感到惊讶。

标签: css performance optimization browser


【解决方案1】:

..我可以做任何额外的微优化吗?

由于您是根据索引选择元素并为它们提供相应的 content 值,因此您可以使用 counter-increment 自动执行此操作,假设此模式是线性的(正如您的 CSS 建议的那样):

ol {
    list-style-type: none;
    counter-reset: item 0;
}
ol > li {
    counter-increment: item;
}
ol.red-numbers > li:before {
    content: counter(item) " pseudo-element ";
    color: #A71930;
    padding-right: 5px;
}
<ol class="red-numbers">
    <li>List</li>
    <li>List</li>
    <li>List</li>
    <li>List</li>
    <li>List</li>
</ol>

【讨论】:

  • 问题出现了如果这确实是一个优化。考虑到此代码需要浏览器进行计算(计数)而不是仅绘制画布,我很想知道您的方法是否确实更快,而不是 - 正如我在更大范围内所期望的那样 - 更慢。
  • @BramVanroy 好点。但考虑到 OP 提到“消除空白”,我认为它们意味着减少样式表中的字节。不过不确定。考虑到列表是自动编号的,这有点奇怪。
【解决方案2】:

Steve souders 进行了广泛的分析。查看这篇文章

http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/.

最大的惊喜是增量从基线到 最复杂、性能最差的测试页面。平均减速 在所有浏览器中为 50 毫秒。

所以实际上我猜这并不重要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多