Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Escrevendo CSS eficiente

O documento seguinte esboça regras para otimizar arquivos CSS para uso no Mozilla UI. A primeira seção é uma discussão geral de como o Mozilla renderiza as regras. Com a compreensão deste sistema, as seguintes seções contém diretrizes de como escrever regras para uma renderização mais rápida e melhor implementação do sistema do Mozilla.

Como o sistema de estilo quebra regras

O sistema de estilo quebra regras acima de quatro categorias primárias. É crítico entender estas categorias, como se fossem a primeira linha de defesa tanto quanto as regras de uma partida são interessantes. Uso o termo seletor de chave nos parágrafos que se seguem. O seletor de chave é definido por ser a mais correta ocorrência de um seletor de id, um seletor de classe ou um seletor de tags.

Regras ID

A primeira categoria consiste nestas regras que têm um seletor de ID como seu seletor de chave.

Exemplos

button#backButton { } /* Esta é uma regra de ID categorizada */
#urlBar[type="autocomplete"] { } /* Esta é uma regra de ID categorizada */
treeitem > treerow > treecell#myCell :active { } /* Esta é uma regra de ID categorizada */

Regras Classe

Se uma regra tem uma classe especificada como seu seletor de chave, então ela cairá nesta categoria.

Exemplos

button.toolbarButton { } /* Uma regra baseada em classe */
.fancyText { } /* Uma regra baseada em classe */
menuitem > .menu-left[checked="true"] { } /* Uma regra baseada em classe */

Regras Tag

Se não for especificado uma classe ou ID como o seletor de chave, então a próxima categoria potencial pra uma regra é a categoria tag. Se uma regra tem uma especificação tag como seu seletor de chave, então esta regra cairá nesta categoria.

Exemplos

td { } /* Uma regra baseada em tag */
treeitem > treerow { } /* Uma regra baseada em tag */
input[type="checkbox"] { } /* Uma regra baseada em tag */

Regras universais

Todas as outras regras cairão nesta categoria.

Exemplos

:table { } /* Uma regra universal */
[hidden="true"] { } /* Uma regra universal */
* { } /* Uma regra universal */
tree > [collapsed="true"] { } /* Uma regra universal */

How the Style System Matches Rules

The style system matches a rule by starting with the rightmost selector and moving to the left through the rule's selectors. As long as your little subtree continues to check out, the style system will continue moving to the left until it either matches the rule or bails out because of a mismatch.

Your first line of defense is the rule filtering that occurs based on the type of the key selector. The purpose of this categorization is to filter out rules so that you don't even have to waste time trying to match them. This is the key to dramatically increasing performance. The fewer rules that you even have to check for a given element, the faster style resolution will be. As an example, if your element has an ID, then only ID rules that match your element's ID will be checked. Only class rules for a class found on your element will be checked. Only tag rules that match your tag will be checked. Universal rules will always be checked.

O documento seguinte esboça regras para otimizar arquivos CSS para uso no Mozilla UI. A primeira seção é uma discussão geral de como o Mozilla renderiza as regras. Com a compreensão deste sistema, as seguintes seções contém diretrizes de como escrever regras para uma renderização mais rápida e melhor implementação do sistema do Mozilla.

Como o sistema de estilo quebra regras

O sistema de estilo quebra regras acima de quatro categorias primárias. É crítico entender estas categorias, como se fossem a primeira linha de defesa tanto quanto as regras de uma partida são interessantes. Uso o termo seletor de chave nos parágrafos que se seguem. O seletor de chave é definido por ser a mais correta ocorrência de um seletor de id, um seletor de classe ou um seletor de tags.

Regras ID

A primeira categoria consiste nestas regras que têm um seletor de ID como seu seletor de chave.

Exemplos

button#backButton { } /* Esta é uma regra de ID categorizada */
#urlBar[type="autocomplete"] { } /* Esta é uma regra de ID categorizada */
treeitem > treerow > treecell#myCell :active { } /* Esta é uma regra de ID categorizada */

Regras Classe

Se uma regra tem uma classe especificada como seu seletor de chave, então ela cairá nesta categoria.

Exemplos

button.toolbarButton { } /* Uma regra baseada em classe */
.fancyText { } /* Uma regra baseada em classe */
menuitem > .menu-left[checked="true"] { } /* Uma regra baseada em classe */

Regras Tag

Se não for especificado uma classe ou ID como o seletor de chave, então a próxima categoria potencial pra uma regra é a categoria tag. Se uma regra tem uma especificação tag como seu seletor de chave, então esta regra cairá nesta categoria.

Exemplos

td { } /* Uma regra baseada em tag */
treeitem > treerow { } /* Uma regra baseada em tag */
input[type="checkbox"] { } /* Uma regra baseada em tag */

Regras universais

Todas as outras regras cairão nesta categoria.

Exemplos

:table { } /* Uma regra universal */
[hidden="true"] { } /* Uma regra universal */
* { } /* Uma regra universal */
tree > [collapsed="true"] { } /* Uma regra universal */

How the Style System Matches Rules

The style system matches a rule by starting with the rightmost selector and moving to the left through the rule's selectors. As long as your little subtree continues to check out, the style system will continue moving to the left until it either matches the rule or bails out because of a mismatch.

Your first line of defense is the rule filtering that occurs based on the type of the key selector. The purpose of this categorization is to filter out rules so that you don't even have to waste time trying to match them. This is the key to dramatically increasing performance. The fewer rules that you even have to check for a given element, the faster style resolution will be. As an example, if your element has an ID, then only ID rules that match your element's ID will be checked. Only class rules for a class found on your element will be checked. Only tag rules that match your tag will be checked. Universal rules will always be checked.

Regras para um CSS Eficiente

Evite seletores universais!

Certifique-se que as regras não terminam na categoria universal!

Não determine seletores de ID  com nome de tags ou classes

Se você tem uma folha de estilos com um seletor de ID, não é necessário adicionar o nome da tag. Os IDs são únicos, então você está deixando a execução mais lenta sem razão.

  • MAU - button#voltar { }
  • MAU - .menu-esq#novoIconeDoMenu { }
  • BOM - #voltar { }
  • BOM - #novoIconeDoMenu { }

Não determine seletores de classe com nome de tags

Similar a regra acima, todas as nossas classes serão únicas. É adequado que você adicione o nome da tag ao nome da classe.

  • MAU - treecell.indentada { }
  • BOM - .treecell-indentada { }

Tente fazer os seletores o mais específico possível!

A única grande causa da desaceleração da execução é ter muitos seletores na categoria de tag. Adicionando classes aos nossos elementos, os podemos dividir estes seletores em categorias de classes, então não temos de perder tempo tentando ligar várias regras a uma tag.

  • MAU - treeitem[mailfolder="true"] > treerow > treecell { }
  • BOM - .treecell-mailfolder { }

Evite seletores descendentes!

O seletor descendente é o mais lento no CSS. É terrívelmente lento, especialmente se uma regra usando o seletor é em uma tag ou na categoria universal. Frequentemente o que é tentado fazer é o seletor de elemento filho. O uso de seletores descendentes é proíbido na UI CSS sem a aprovação explícita do seu skin's module owner.

  • MAU - treehead treerow treecell { }
  • MELHOR, MAS CONTINUA RUIM (veja a próxima regra) - treehead > treerow > treecell { }

Regras de tag não devem ter seletores de elemento filho!

Evite usar seletores de elemento filho com regras de tag. Você irá aumentar dramáticamente o tempo de renderização (especialmente se a regra tem mais chances de ser aplicada que não) para todas as ocorrências do elemento.

  • MAU - treehead > treerow > treecell { }
  • O MELHOR - .treecell-topo { }

Questione todos os usos dos seletores filho!

Seja cauteloso quando usa seletor de elemento filho. If you can come up with a way to avoid having to use it, do so. 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 attributes from RDF can be duplicated in a template! Take advantage of this fact to duplicate RDF properties on child XUL elements that wish to change based off that attribute.

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

Rely on inheritance!

Learn which properties inherit, and allow them to do so! We have explicitly set up XUL widgetry so that you can put list-style-image (just one example) or font rules on the parent tag, and it will filter in to the anonymous content. You don't have to waste time writing a rule that talks directly to the 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 the anonymous content (without understanding that list-style-image inherits) resulted in a rule that was in the class category, when this rule really should have ended up being in the most specific category of all, the ID category.

Remember, especially with anonymous content, that they all have the same classes! The bad rule above causes the icon of every menu to be checked to see if it is contained in the bookmarks menu item. This is hideously expensive (since there are many menus); this rule never should have even been checked by any menu other than 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.

Informações Sobre o Documento Original

  • Autor(es): David Hyatt
  • Outros Contribuidores: David Tobias Nunes
  • Última Atualização 12/06/2007

Categorias

Interwiki Language Links

Etiquetas do documento e colaboradores

Etiquetas: 
 Colaboradores para esta página: teoli, guerreirogabriel, Verruckt, Totalninja, Luis Henrique Sousa
 Última atualização por: teoli,