MDN’s new design is in Beta! A sneak peek:

Scrivere CSS in modo efficace

Questo documento contiene delle linee guida per ottimizzare il codice CSS e in particolare come scrivere selettori precisi ed efficienti.

La specificazione CSS non specifica come i browser implementato il sistema di stile ma semplicemente cosa fa. Il perchè di questo è che i diversi sistemi di stili possono avere performance completamente diverse, specialmente Gecko e Webkit che essendo open source implementa un algoritmo simile e con molti punti di forza in comune. Perciò, I consigli presentati qui saranno utili per veri siti per il web.

La prima parte è una discussione generale su come il sistema di stile che si usa di solito ha delle regole. La seguente sezione ha delle linee guida per scrivere regole che hanno vantaggi sullo implementare uno stile.

Come lo stile infrange le regole

Lo stile infrange le regole in quattro modi:

  1. Regole degli ID
  2. Regole delle classi
  3. Regole dei TAG
  4. Regole universali

È necessario capire questo in quanto sono i fondamenti delle regole di congruenza.

Userò il termino selettore chiave nei paragrafi che seguono. Il selettore chiave è l'ultima parte del selettore (la parte che incontra gli elementi principali piuttosto che gli elementi antenati).

Un esempio nella regola...

a img, div > p, h1 + [title] {…}

…I selettori chiave sono img, p e title.

ID rules

The first category consists of those rules that have an ID selector as their key selector.

button#backButton {…} /* This is an ID-categorized rule */
#urlBar[type="autocomplete"] {…} /* This is an ID-categorized rule */
treeitem > treerow > treecell#myCell:active {…} /* This is an ID-categorized rule */

Class rules

If a rule has a class specified as its key selector, then it falls into this category.

button.toolbarButton {…} /* A class-based rule */
.fancyText {…}	/* A class-based rule */
menuitem > .menu-left[checked="true"] {…} /* A class-based rule */

Tag rules

If no class or ID is specified as the key selector, the next candidate is the tag category. If a rule has a tag specified as its key selector, then the rule falls into this category.

td {…} /* A tag-based rule */
treeitem > treerow {…} /* A tag-based rule */
input[type="checkbox"] {…} /* A tag-based rule */

Universal rules

All other rules fall into this category.

[hidden="true"] {…} /* A universal rule */  
* {…}		/* A universal rule */
tree > [collapsed="true"] {…} /* A universal rule */

How the style system matches rules

The style system matches rules by starting with the key selector, then moving to the left (looking for any ancestors in the rule’s selector). As long as the selector’s subtree continues to check out, the style system continues moving to the left until it either matches the rule, or abandons because of a mismatch.

The most fundamental concept to learn is this rule filtering. The categories exist in order to filter out irrelevant rules (so the style system doesn’t waste time trying to match them).

This is the key to dramatically increasing performance. The fewer rules required to check for a given element, the faster style resolution will be.

For example, if an element has an ID, then only ID rules that match the element’s ID will be checked. Only Class Rules for a class found on the element will be checked. Only Tag Rules that match the tag will be checked. Universal Rules will always be checked.

Guidelines for efficient CSS

Avoid universal rules

Make sure a rule doesn’t end up in the universal category!

Don’t qualify ID rules with tag names or classes

If a rule has an ID selector as its key selector, don’t add the tag name to the rule. Since IDs are unique, adding a tag name would slow down the matching process needlessly.

button#backButton {…}
.menu-left#newMenuIcon {…}
#backButton {…}
#newMenuIcon {…}
Exception: 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.

Don’t qualify class rules with tag names

The previous concept also applies here.  Though classes can be used many times on the same page, they are still more unique than a tag.

One convention you can use is to include the tag name in the class name.  However, this may cost some flexibility; if design changes are made to the tag, the class names must be changed as well.  (It’s best to choose strictly semantic names, as such flexibility is one of the aims of separate stylesheets.)

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

Use the most specific category possible

The single biggest cause of slowdown is too many rules in the tag category. By adding classes to our elements, we can further subdivide these rules into Class Categories, which eliminates time spent trying to match rules for a given tag.

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

Avoid the descendant selector

The descendant selector is the most expensive selector in CSS. It is dreadfully expensive—especially if the selector is in the Tag or Universal Category.

Frequently, what is really desired is the child selector.  For instance, the performances are so bad, that descendant selectors are banned in Firefox' User Interface CSS, without a specific justification. It's a good idea to do the same on your Web pages

treehead treerow treecell {…}
BETTER, BUT STILL BAD (see next guideline)
treehead > treerow > treecell {…}

Tag category rules should never contain a child selector

Avoid using the child selector with tag category rules. This will dramatically lengthen the match time (especially if the rule is likely to be matched) for all occurrences of that element.

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

Question all usages of the child selector

Exercise caution when using the child selector. Avoid it if you can.

In particular, the child selector is frequently used with RDF trees and menus like so:

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

Remember that REF attributes can be duplicated in a template! Take advantage of this.  Duplicate RDF properties on child XUL elements in order to change them based on the attribute.

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

Rely on inheritance

Learn which properties inherit, and allow them to do so!  

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.

#bookmarkMenuItem > .menu-left { list-style-image: url(blah) }
#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!

If you're developing Mozilla-specific code: 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.

Original Document Information

Tag del documento e collaboratori

 Hanno collaborato alla realizzazione di questa pagina: MattewDeveloper, plissken
 Ultima modifica di: MattewDeveloper,