Writing efficient CSS

  • Revision slug: Web/Guide/CSS/Writing_efficient_CSS
  • Revision title: Writing efficient CSS
  • Revision id: 495171
  • Created:
  • Creator: kscarfone
  • Is current revision? No
  • Comment Updated tags

Revision Content

This document provides guidelines for optimizing CSS code, and more specifically on how to write efficient selectors.

The CSS specification doesn't specify how browsers must implement the style system, merely what it must do. Because of this, different style system engines may have completely different performance behaviors, and especially Gecko and WebKit which are open source, implement similar algorithms, with very similar strengths and weaknesses. Therefore the tips presented here should be useful for real-world Web documents.

The first section is a general discussion of how the usual style system categorizes rules. The following sections contain guidelines for writing rules that take advantage of such a style system implementation.

How the style system breaks up rules

The style system breaks rules up into four primary categories:

  1. ID Rules
  2. Class Rules
  3. Tag Rules
  4. Universal Rules

It is critical to understand these categories, as they are the fundamental building blocks of rule matching.

I use the term key selector in the paragraphs that follow. The key selector is the last part of the selector (the part that matches the element being matched, rather than its ancestors).

For example, in the rule…

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

…the key selectors are img, p, and title.

ID rules

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

Example
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.

Example
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.

Example
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.

Example
[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.

BAD
button#backButton {…}
BAD
.menu-left#newMenuIcon {…}
GOOD
#backButton {…}
GOOD
#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.)

BAD
treecell.indented {…}
GOOD
.treecell-indented {…}
BEST
.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.

BAD
treeitem[mailfolder="true"] > treerow > treecell {…}
GOOD
.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

BAD
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.

BAD
treehead > treerow > treecell {…}
GOOD
.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:

BAD
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.

GOOD
.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.

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!

If you're developing Mozilla-specific code: Putting a bunch of images into a single image file and selecting them with {{ Cssxref("-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

{{ languages( { "es": "es/CSS/Escribir_CSS_eficiente", "ja": "ja/Writing_Efficient_CSS" } ) }}

Revision Source

<p><span class="seoSummary">This document provides guidelines for optimizing CSS code, and more specifically on how to write efficient selectors.</span></p>
<p>The CSS specification doesn't specify how browsers must implement the style system, merely what it must do. Because of this, different style system engines may have completely different performance behaviors, and especially Gecko and WebKit which are open source, implement similar algorithms, with very similar strengths and weaknesses. Therefore the tips presented here should be useful for real-world Web documents.</p>
<p>The first section is a general discussion of how the usual style system categorizes rules. The following sections contain guidelines for writing rules that take advantage of such a style system implementation.</p>
<h2 id="How_the_style_system_breaks_up_rules" name="How_the_style_system_breaks_up_rules">How the style system breaks up rules</h2>
<p>The style system breaks rules up into four primary categories:</p>
<ol>
 <li>ID Rules</li>
 <li>Class&nbsp;Rules</li>
 <li>Tag&nbsp;Rules</li>
 <li>Universal&nbsp;Rules</li>
</ol>
<p>It is critical to understand these categories, as they are the fundamental building blocks of rule matching.</p>
<p>I use the term <em>key selector</em> in the paragraphs that follow. The key selector is the last part of the selector (the part that matches the element being matched, rather than its ancestors).</p>
<p>For example, in the rule…</p>
<pre class="brush: css">
a img, div &gt; p, h1 + [title] {…}
</pre>
<p>…the key selectors are <code>img</code>, <code>p</code>, and <a href="/en/HTML/Element/title" title="en/HTML/Element/title"><code>title</code></a>.</p>
<h3 id="ID_Rules" name="ID_Rules">ID rules</h3>
<p>The first category consists of those rules that have an <code>ID</code> selector as their key selector.</p>
<h5 id="Example">Example</h5>
<pre class="brush: css">
button#backButton {…} /* This is an ID-categorized rule */
#urlBar[type="autocomplete"] {…} /* This is an ID-categorized rule */
treeitem &gt; treerow &gt; treecell#myCell:active {…} /* This is an ID-categorized rule */
</pre>
<h3 id="Class_Rules" name="Class_Rules">Class rules</h3>
<p>If a rule has a <code>class</code> specified as its key selector, then it falls into this category.</p>
<h5 id="Example">Example</h5>
<pre class="brush: css">
button.toolbarButton {…} /* A class-based rule */
.fancyText {…}	/* A class-based rule */
menuitem &gt; .menu-left[checked="true"] {…} /* A class-based rule */
</pre>
<h3 id="Tag_Rules" name="Tag_Rules">Tag rules</h3>
<p>If no <code>class</code> or <code>ID</code> is specified as the key selector, the next candidate is the <strong>tag</strong> category. If a rule has a tag specified as its key selector, then the rule falls into this category.</p>
<h5 id="Example">Example</h5>
<pre class="brush: css">
td {…} /* A tag-based rule */
treeitem &gt; treerow {…} /* A tag-based rule */
input[type="checkbox"] {…} /* A tag-based rule */
</pre>
<h3 id="Universal_Rules" name="Universal_Rules">Universal rules</h3>
<p>All other rules fall into this category.</p>
<h5 id="Example">Example</h5>
<pre class="brush: css">
[hidden="true"] {…} /* A universal rule */  
* {…}		/* A universal rule */
tree &gt; [collapsed="true"] {…} /* A universal rule */
</pre>
<h2 id="How_the_Style_System_Matches_Rules" name="How_the_Style_System_Matches_Rules">How the style system matches rules</h2>
<p>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.</p>
<p>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).</p>
<p><strong>This is the key to dramatically increasing performance.</strong> The fewer rules required to check for a given element, the faster style resolution will be.</p>
<p>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.</p>
<h2 id="Guidelines_for_Efficient_CSS" name="Guidelines_for_Efficient_CSS">Guidelines for efficient CSS</h2>
<h3 id="Avoid_Universal_Rules.21" name="Avoid_Universal_Rules.21">Avoid universal rules</h3>
<p>Make sure a rule doesn’t end up in the universal category!</p>
<h3 id="Don.27t_qualify_ID-categorized_rules_with_tag_names_or_classes" name="Don.27t_qualify_ID-categorized_rules_with_tag_names_or_classes">Don’t qualify ID rules with tag names or classes</h3>
<p><strong>If a rule has an ID selector as its key selector, don’t add the tag name to the rule.</strong> Since IDs are unique, adding a tag name would slow down the matching process needlessly.</p>
<dl style="margin: 1em 12.5%">
 <dt>
  <span class="incorrect">BAD</span></dt>
 <dd>
  <code>button#backButton {…}</code></dd>
 <dt>
  <span class="incorrect">BAD</span></dt>
 <dd>
  <code>.menu-left#newMenuIcon {…}</code></dd>
 <dt>
  <span class="correct">GOOD</span></dt>
 <dd>
  <code>#backButton {…}</code></dd>
 <dt>
  <span class="correct">GOOD</span></dt>
 <dd>
  <code>#newMenuIcon {…}</code></dd>
</dl>
<div class="note">
 <strong>Exception:</strong> When it’s desirable to change the <code>class</code> of an element dynamically in order to apply different styles in different situations, but the same <code>class</code> is going to be shared with other elements.</div>
<h3 id="Don.27t_qualify_class-categorized_rules_with_tag_names" name="Don.27t_qualify_class-categorized_rules_with_tag_names">Don’t qualify class rules with tag names</h3>
<p>The previous concept also applies here.&nbsp; Though classes can be used many times on the same page, they are still more unique than a tag.</p>
<p>One convention you can use is to include the tag name <em>in</em> the class name. &nbsp;However, this may cost some flexibility; if design changes are made to the tag, the class names must be changed as well. &nbsp;(It’s best to choose strictly semantic names, as such flexibility is one of the aims of separate stylesheets.)</p>
<dl style="margin: 1em 12.5%">
 <dt>
  <span class="incorrect">BAD</span></dt>
 <dd>
  <code>treecell.indented {…}</code></dd>
 <dt>
  <span class="correct">GOOD</span></dt>
 <dd>
  <code>.treecell-indented {…}</code></dd>
 <dt>
  <span class="best">BEST</span></dt>
 <dd>
  <code>.hierarchy-deep {…}</code></dd>
</dl>
<h3 id="Try_to_put_rules_into_the_most_specific_category_you_can.21" name="Try_to_put_rules_into_the_most_specific_category_you_can.21">Use the most specific category possible</h3>
<p><strong>The single biggest cause of slowdown is too many rules in the tag category. </strong>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.</p>
<dl style="margin: 1em 12.5%">
 <dt>
  <span class="incorrect">BAD</span></dt>
 <dd>
  <code>treeitem[mailfolder="true"] &gt; treerow &gt; treecell {…}</code></dd>
 <dt>
  <span class="correct">GOOD</span></dt>
 <dd>
  <code>.treecell-mailfolder {…}</code></dd>
</dl>
<h3 id="Avoid_the_descendant_selector.21" name="Avoid_the_descendant_selector.21">Avoid the descendant selector</h3>
<p><strong>The descendant selector is the most expensive selector in CSS.</strong> It is <em>dreadfully</em> expensive—especially if the selector is in the Tag or Universal Category.</p>
<p>Frequently, what is really desired is <strong>the child selector</strong>.&nbsp; 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</p>
<dl style="margin: 1em 12.5%">
 <dt>
  <span class="incorrect">BAD</span></dt>
 <dd>
  <code>treehead treerow treecell {…}</code></dd>
 <dt>
  <span class="incorrect">BETTER, BUT STILL BAD (see next guideline)</span></dt>
 <dd>
  <code>treehead &gt; treerow &gt; treecell {…}</code></dd>
</dl>
<h3 id="Tag-categorized_rules_should_never_contain_a_child_selector.21" name="Tag-categorized_rules_should_never_contain_a_child_selector.21">Tag category rules should <em>never</em> contain a child selector</h3>
<p><strong>Avoid using the child selector with tag category rules.</strong> This will dramatically lengthen the match time (especially if the rule is likely to be matched) for all occurrences of that element.</p>
<dl style="margin: 1em 12.5%">
 <dt>
  <span class="incorrect">BAD</span></dt>
 <dd>
  <code>treehead &gt; treerow &gt; treecell {…}</code></dd>
 <dt>
  <span class="correct">GOOD</span></dt>
 <dd>
  <code>.treecell-header {…}</code></dd>
</dl>
<h3 id="Question_all_usages_of_the_child_selector.21" name="Question_all_usages_of_the_child_selector.21">Question all usages of the child selector</h3>
<p><strong>Exercise caution when using the child selector.</strong> Avoid it if you can.</p>
<p>In particular, the child selector is frequently used with RDF trees and menus like so:</p>
<dl style="margin: 1em 12.5%">
 <dt>
  <span class="incorrect">BAD</span></dt>
 <dd>
  <code>treeitem[</code><code>IsImapServer="true"</code><code>] &gt; treerow &gt; .tree-folderpane-icon {…}</code></dd>
</dl>
<p>Remember that REF attributes can be duplicated in a template! Take advantage of this. &nbsp;Duplicate RDF properties on child XUL elements in order to change them based on the attribute.</p>
<dl style="margin: 1em 12.5%">
 <dt>
  <span class="correct">GOOD</span></dt>
 <dd>
  <code>.tree-folderpane-icon[IsImapServer="true"] {…}</code></dd>
</dl>
<h3 id="Rely_on_inheritance.21" name="Rely_on_inheritance.21">Rely on inheritance</h3>
<p>Learn which properties inherit, and allow them to do so! &nbsp;</p>
<p>For example, XUL widgets are explicitly set up such that a parent’s&nbsp;<code>list-style-image</code>&nbsp;or <code>font</code> rules will filter down to anonymous content. It’s not necessary to waste time on rules that talk directly to anonymous content.</p>
<dl style="margin: 1em 12.5%">
 <dt>
  <span class="incorrect">BAD</span></dt>
 <dd>
  <code>#bookmarkMenuItem &gt; .menu-left { list-style-image: url(blah) }</code></dd>
 <dt>
  <span class="correct">GOOD</span></dt>
 <dd>
  <code>#bookmarkMenuItem { list-style-image: url(blah) }</code></dd>
</dl>
<p>In the above example, the desire to style anonymous content (without leveraging the inheritance of&nbsp;<code>list-style-image</code>) resulted in a rule that was in the Class&nbsp;Category, when the rule should have ended up in the ID&nbsp;Category—the most specific category of all!</p>
<p><strong>Remember:</strong> Elements all have the same classes—especially anonymous content!</p>
<p>The above “bad” rule forces every menu’s icons to be tested for containment within the bookmarks menu item.&nbsp;Since there are many menus,&nbsp;this is extraordinarily expensive. &nbsp;Instead, the “good” rule limits the testing to the bookmarks menu.</p>
<h3 id="Use_-moz-image-region.21" name="Use_-moz-image-region.21">Use <code>-moz-image-region</code>!</h3>
<p>If you're developing Mozilla-specific code: Putting a bunch of images into a single image file and selecting them with <code>{{ Cssxref("-moz-image-region") }}</code> performs significantly better than putting each image into its own file.</p>
<h3 id="Use_scoped_stylesheets">Use scoped stylesheets</h3>
<p>If you specify a stylesheet as an XBL&nbsp;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.</p>
<div class="originaldocinfo">
 <h3 id="Original_Document_Information" name="Original_Document_Information">Original Document Information</h3>
 <ul>
  <li>Author: David Hyatt</li>
  <li>Original Document Date: 2000-04-21</li>
  <li>Original Document URL: <a class="external" href="http://www.mozilla.org/xpfe/goodcss.html" rel="freelink">http://www.mozilla.org/xpfe/goodcss.html</a></li>
 </ul>
</div>
<p>{{ languages( { "es": "es/CSS/Escribir_CSS_eficiente", "ja": "ja/Writing_Efficient_CSS" } ) }}</p>
Revert to this revision