高效 css 整理


避免通用规则

请确保规则不以通用类型作为结束!

不要用标签名或 classes 来限制 ID 规则

如果规则的关键选择器为 ID 选择器,则没有必要为规则增加标签名。因为 ID 是唯一的,增加标签只会拖慢匹配过程。

button#backButton {…}
.menu-left#newMenuIcon {…}
#backButton {…}
#newMenuIcon {…}
例外:When it’s desirable to change the class of an element dynamically in order to apply different styles in different situations, but the same class is going to be shared with other elements.

不要用标签名限制 class 规则

前面那节内容在这里同样适用。虽然在同一页面能够多次使用 class,但它仍然比标签名更独特。

按照惯例,你可以将标签名写到 class 名里。当然,这会有损灵活性;如果设计更改,标签变动,class 名也要跟着变动。(最好的办法是选择严格语义化的名字,毕竟分离样式表的一个目标就是为了灵活性。)

treecell.indented {…}
.treecell-indented {…}
.hierarchy-deep {…}

尽量使用最具体的类别

解析速度变慢的最大原因就是绝大多数规则都落进了标签类别中。为元素增加 class,我们就可以进一步的将这些规则划分到 Class 类别中,这将减少用于匹配标签的时间。

treeitem[mailfolder="true"] > treerow > treecell {…}
.treecell-mailfolder {…}

避免后代选择器

后代选择器是 CSS 中耗费最昂贵的选择器。 它的耗费是极其昂贵的—特别是当选择器在标签或通用类别中。

通常我们在意的是 子选择器。比如说,当性能十分差的时候,Firefox 的 UI  CSS 将不需要任何理由的禁止掉子选择器。你也应该在网页中这么做。

treehead treerow treecell {…}
略好,但还是差(查看下一条指南)
treehead > treerow > treecell {…}

属于标签类别的规则永远不要包含子选择器

标签类别的规则中避免使用子选择器。否则的话,在该元素出现的所有地方,匹配时间都将极大延长(特别是当规则很可能会被匹配) 。

treehead > treerow > treecell {…}
.treecell-header {…}

在使用子选择器的地方想想为什么

当使用子选择器时要十分谨慎。能免则免。

一般来说,子选择器常常用于 RDF 树与菜单:

treeitem[IsImapServer="true"] > treerow > .tree-folderpane-icon {…}

要记住,模板中的 REF 特性可以重复出现!好好利用这一优点。在子 XUL 元素上重复使用 RDF 属性,这样可以基于该属性来修改元素。

GOOD
.tree-folderpane-icon[IsImapServer="true"] {…}

依赖继承

了解哪些属性能够继承,然后允许它们这样做!

For example, XUL widgets are explicitly set up such that a parent’s list-style-image or font rules will filter down to anonymous content. It’s not necessary to waste time on rules that talk directly to anonymous content.

BAD
#bookmarkMenuItem > .menu-left { list-style-image: url(blah) }
GOOD
#bookmarkMenuItem { list-style-image: url(blah) }

In the above example, the desire to style anonymous content (without leveraging the inheritance of list-style-image) resulted in a rule that was in the Class Category, when the rule should have ended up in the ID Category—the most specific category of all!

Remember: Elements all have the same classes—especially anonymous content!

The above “bad” rule forces every menu’s icons to be tested for containment within the bookmarks menu item. Since there are many menus, this is extraordinarily expensive.  Instead, the “good” rule limits the testing to the bookmarks menu.

Use -moz-image-region!

Putting a bunch of images into a single image file and selecting them with -moz-image-region performs significantly better than putting each image into its own file.

Use scoped stylesheets

If you specify a stylesheet as an XBL resource, the styles only apply to the bound elements and their anonymous content. This reduces the inefficiency of universal rules and child selectors because there are fewer elements to consider.

原文地址:https://www.cnblogs.com/yingwo/p/4527470.html