Reforce isso, concordando com estas guidelines todas as vezes. Pequenos ou grandes, mostre o que está incorreto. Para adições ou contribuições para este Guia de Código, por favor abra uma Issue no Github.
46 |
47 |
48 |
49 |
Toda linha de código deve parecer que foi escrita por uma única pessoa, não importa a quantidade de contribuidores.
50 |
51 |
52 |
53 |
54 |
55 |
HTML
56 |
57 |
58 |
59 |
60 |
Sintaxe do HTML
61 |
62 |
Use soft-tabs com dois espaços.
63 |
Elementos aninhados devem estar identados uma vez (2 espaços).
64 |
Sempre use aspas duplas, nunca aspas simples.
65 |
Nunca inclua uma barra invertida nos elementos viúvos (exemplo: <img> ou <hr>).
66 |
67 |
68 |
69 | {% highlight html %}{% include html/syntax.html %}{% endhighlight %}
70 |
71 |
72 |
73 |
74 |
75 |
Doctype do HTML5
76 |
Reforce os padrões com este simples doctype no início de todas as páginas HTML.
77 |
78 |
79 | {% highlight html %}{% include html/doctype.html %}{% endhighlight %}
80 |
81 |
82 |
83 |
84 |
85 |
Encoding de caractéres
86 |
Assegure-se rapidamente a renderização do seu conteúdo declarando o encoding de caractéres explicitamente.
87 |
88 |
89 | {% highlight html %}{% include html/encoding.html %}{% endhighlight %}
90 |
91 |
92 |
93 |
94 |
95 |
Inserindo CSS e JavaScript
96 |
De acordo com as especificações do HTML5, não há necessidade de especificar um atributo type quando incluímos arquivos de CSS e JavaScript como text/css e text/javascript.
A presença de um atributo boleano representa um valor verdadeiro e a ausência do atributo representa um valor falso.
142 |
143 |
Se você precisa incluir valores nos atributos, você não precisa seguir esta regra do WhatWG:
144 |
145 |
Se o atributo está presente, seu valor deve ser uma string vazia ou [...] o nome canônico do atributo, sem espaços em branco.
146 |
147 |
Resumindo, não adicione nenhum valor.
148 |
149 |
150 | {% highlight html %}{% include html/boolean-attributes.html %}{% endhighlight %}
151 |
152 |
153 |
154 |
155 |
156 |
Reduzindo o markup
157 |
Sempre que possível, evite elementos pais supérfluos quando escrever HTML. Muitas vezes é necessário uma interação ou refatoração, mas isso produz pouco HTML. Veja o seguinte exemplo:
158 |
159 |
160 | {% highlight html %}{% include html/reducing-markup.html %}{% endhighlight %}
161 |
162 |
163 |
164 |
165 |
166 |
Markup gerado por Javascript
167 |
Escrever código em um arquivos Javascript faz com que o conteúdo seja difícil de ser encontrado, difícil de ser editado e o torna menos performático. Evite fazer isso o máximo possível.
168 |
169 |
170 |
171 |
172 |
CSS
173 |
174 |
175 |
176 |
177 |
Sintaxe do CSS
178 |
179 |
Use soft-tabs com dois espaços.
180 |
Quando agrupar seletores, deixe seletores individuais em uma linha.
181 |
Inclua um espaço antes de abrir um colchete.
182 |
Coloque o fechamento do colchete em uma nova linha.
183 |
Inclua um espaço depois dos dois pontos : em cada declaração de propriedade.
184 |
Cada declaração deve estar em sua própria linha para encontrarmos melhor os erros.
185 |
Feche todas as declarações com ponto-vírgula ;.
186 |
Valores separados por vírgula devem incluir um espaço logo depois da vírgula (ex., box-shadow).
187 |
Não inclua espaços depois das vírgulas como em cores <rgb(), rgba(), hsl(), hsla() ou rect(). Isto ajuda a diferenciar múltiplos valores (vírgulas, sem espaço) de cores de propriedades múltiplas (vírgulas, com espaço). Também não coloque valores iniciados com zero (ex., .5 em vez de 0.5).
188 |
Deixe todos os valores hexadecimais em caixa baixa, exemplo: #fff. Letras com caixa baixa são mais fáceis de serem lidas e entendidas quando queremos scanear o documento.
189 |
Valores separados por vírgula devem incluir um espaço logo depois da vírgula.
190 |
Não inclua espaços depois das vírgulas como em cores rgb() ou rgba() e não inicie valores com zero.
191 |
Deixe todos os valores hexadecimais em caixa baixa, exemplo: #fff.
192 |
Use cores em hexadecimal abrevidas quando puder, exemplo: #fff em vez de #ffffff.
193 |
Coloque aspas nos valores em seletores com atributos, exemplo: input[type="text"].
194 |
Evite especificar unidades quando os valores forem 0, exemplo: margin: 0; em vez de margin: 0px;.
Declarações relacionadas devem ser agrupadas segundo a seguinte ordem:
207 |
208 |
Posicionamento
209 |
Box model
210 |
Tipografia
211 |
Visual
212 |
213 |
Posicionamento vem primeiro por que isto pode remover um elemento do fluxo normal do documento e substituir estilos relacionados. O box model vem depois pois ele dita as dimensões e lugar do componente.
214 |
Tudo o mais que toma lugar dentro do componente ou não impacta as duas seções anteriores, vem por último.
215 |
Para uma lista completa de propridades e suas ordens, por favor veja Recess,
216 |
Declarações relacionadas devem ser agrupadas, colocando posicionamento e as propriedades de box-model perto do topo, seguido das propriedades de tipografia e depois propriedades visuais.
217 |
Para uma lista completa das propriedades e suas ordens, por favor verifique a página do Recess.
Coloque as Media Queries o mais perto possível de suas regras originais. Não as coloque separadas em outros arquivos ou no final do documento. Se você fizer isso, outros poderão não encontrá-las no futuro. Veja um exemplo típico:
Quando usar prefixos de browsers, idente cada propriedade alinhada verticalmente para facilitar a edição multi-linha.
238 |
No Textmate, use Text → Edit Each Line in Selection (⌃⌘A). No Sublime Text 2, use Selection → Add Previous Line (⌃⇧↑) e Selection → Add Next Line (⌃⇧↓).
Em lugares onde são definidas apenas uma linha de propriedade, considere remover as quebras de linha para melhorar a leitura e edição. Considere este exemplo:
Esforce-se muito para usar declarações de propriedades resumidas onde você define todos os valores dessa propriedade. As propriedades resumidas mais usadas incluem:
259 |
260 |
padding
261 |
margin
262 |
font
263 |
background
264 |
border
265 |
border-radius
266 |
267 |
Frequentemente não precisamos definir todos os valores que uma propriedade representa. Por exemplo, os títulos do HTML tem margens no top e bottom definidas por padrão, então, quando necessário, apenas substitua estes dois valores. O uso excessivo de propriedades resumidas (ou shorthand properties) pode fazer com que o código fique um pouco bagunçado quando substituímos propriedades não utilizadas.
268 |
O Mozilla Developer Network tem um ótimo artigo em shorthand properties para quem não está familiarizado essa forma de escrever.
Evite aninhar seletores (fazer "nesting"). Só porque você pode fazer isso, não significa que você deve fazê-lo sempre. Considere aninhar se você tem um escopo de estilos para um pai e se há múltiplos elementos para serem aninhados.
Código é escrito e mantido por pessoas. Certifique-se de que o código é descritivo, bem comentado e amigável para os outros. Grandes pedaços de comentários devem ter contexto e não devem apenas reiterar um nome de classe ou componente.
293 |
Certifique-se de escrever em sentenças completas ou grandes comentários e frases sucintas para notas gerais.
Enforce these, or your own, agreed upon guidelines at all times. Small or large, call out what's incorrect. For additions or contributions to this Code Guide, please open an issue on GitHub.
47 |
48 |
49 |
50 |
Every line of code should appear to be written by a single person, no matter the number of contributors.
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
HTML
59 |
60 |
61 |
62 |
63 |
Syntax
64 |
65 |
Use soft tabs with two spaces—they're the only way to guarantee code renders the same in any environment.
66 |
Nested elements should be indented once (two spaces).
67 |
Always use double quotes, never single quotes, on attributes.
68 |
Don't include a trailing slash in self-closing elements—the HTML5 spec says they're optional.
69 |
70 |
71 |
72 | {% highlight html %}{% include html/syntax.html %}{% endhighlight %}
73 |
74 |
75 |
76 |
77 |
78 |
HTML5 doctype
79 |
Enforce standards mode and more consistent rendering in every browser possible with this simple doctype at the beginning of every HTML page.
80 |
81 |
82 | {% highlight html %}{% include html/doctype.html %}{% endhighlight %}
83 |
84 |
85 |
86 |
87 |
88 |
Character encoding
89 |
Quickly and easily ensure proper rendering of your content by declaring an explicit character encoding.
90 |
91 |
92 | {% highlight html %}{% include html/encoding.html %}{% endhighlight %}
93 |
94 |
95 |
96 |
97 |
98 |
CSS and JavaScript includes
99 |
Per HTML5 spec, typically there is no need to specify a type when including CSS and JavaScript files as text/css and text/javascript are their respective defaults.
108 | {% highlight html %}{% include html/style-script.html %}{% endhighlight %}
109 |
110 |
111 |
112 |
113 |
114 |
Practicality over purity
115 |
Strive to maintain HTML standards and semantics, but not at the expense of practicality. Use the least amount of markup with the fewest intricacies whenever possible.
116 |
117 |
118 |
119 |
120 |
121 |
Attribute order
122 |
HTML attributes should come in this particular order for easier reading of code.
123 |
124 |
class
125 |
id, name
126 |
data-*
127 |
src, for, type, href
128 |
129 |
Classes make for great reusable components, so they come first. Ids are more specific and should be used sparingly (e.g., for in-page bookmarks), so they come second.
130 |
131 |
132 | {% highlight html %}{% include html/attribute-order.html %}{% endhighlight %}
133 |
134 |
135 |
136 |
137 |
138 |
Boolean attributes
139 |
A boolean attribute is one that needs no declared value. XHTML required you to declare a value, but HTML5 has no such requirement.
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
143 |
144 |
If you must include the attribute's value, and you don't need to, follow this WhatWG guideline:
145 |
146 |
If the attribute is present, its value must either be the empty string or [...] the attribute's canonical name, with no leading or trailing whitespace.
147 |
148 |
In short, don't add a value.
149 |
150 |
151 | {% highlight html %}{% include html/boolean-attributes.html %}{% endhighlight %}
152 |
153 |
154 |
155 |
156 |
157 |
Reducing markup
158 |
Whenever possible, avoid superfluous parent elements when writing HTML. Many times this requires iteration and refactoring, but produces less HTML. Take the following example:
159 |
160 |
161 | {% highlight html %}{% include html/reducing-markup.html %}{% endhighlight %}
162 |
163 |
164 |
165 |
166 |
167 |
JavaScript generated markup
168 |
Writing markup in a JavaScript file makes the content harder to find, harder to edit, and less performant. Avoid it whenever possible.
169 |
170 |
171 |
172 |
173 |
174 |
175 |
CSS
176 |
177 |
178 |
179 |
180 |
Syntax
181 |
182 |
Use soft tabs with two spaces—they're the only way to guarantee code renders the same in any environment.
183 |
When grouping selectors, keep individual selectors to a single line.
184 |
Include one space before the opening brace of declaration blocks for legibility.
185 |
Place closing braces of declaration blocks on a new line.
186 |
Include one space after : for each declaration.
187 |
Each declaration should appear on its own line for more accurate error reporting.
188 |
End all declarations with a semi-colon. The last declaration's is optional, but your code is more error prone without it.
189 |
Comma-separated values should include a space after each comma.
190 |
Don't include spaces after commas withinrgb() or rgba() colors to differentiate color values from CSS properties that allow multiple values that are already separated by a comma and space. Also, don't prefix values with a leading zero (e.g., .5 instead of 0.5).
191 |
Lowercase all hex values, e.g., #fff. Lowercase letters are much easier to discern when scanning a document as they tend to have more unique shapes.
192 |
Use shorthand hex values where available, e.g., #fff instead of #ffffff.
193 |
Quote attribute values in selectors, e.g., input[type="text"]. They’re only optional in some cases, and it’s a good practice for consistency.
194 |
Avoid specifying units for zero values, e.g., margin: 0; instead of margin: 0px;.
Related property declarations should be grouped together following the order:
207 |
208 |
Positioning
209 |
Box model
210 |
Typographic
211 |
Visual
212 |
213 |
Positioning comes first because it can remove an element from the normal flow of the document and override box model related styles. The box model comes next as it dictates a component's dimensions and placement.
214 |
Everything else takes place inside the component or without impacting the previous two sections, and thus they come last.
215 |
For a complete list of properties and their order, please see Recess.
Place media queries as close to their relevant rule sets whenever possible. Don't bundle them all in a separate stylesheet or at the end of the document. Doing so only makes it easier for folks to miss them in the future. Here's a typical setup.
When using vendor prefixed properties, indent each property such that the declaration's value lines up vertically for easy multi-line editing.
236 |
In Textmate, use Text → Edit Each Line in Selection (⌃⌘A). In Sublime Text 2, use Selection → Add Previous Line (⌃⇧↑) and Selection → Add Next Line (⌃⇧↓).
In instances where a rule set includes only one declaration, consider removing line breaks for readability and faster editing. Any rule set with multiple declarations should be split to separate lines.
247 |
The key factor here is error detection—e.g., a CSS validator stating you have a syntax error on Line 183. With a single declaration, there's no missing it. With multiple declarations, separate lines is a must for your sanity.
Strive to limit use of shorthand declarations to instances where you must explicitly set all the available values. Common overused shorthand properties include:
258 |
259 |
padding
260 |
margin
261 |
font
262 |
background
263 |
border
264 |
border-radius
265 |
266 |
Often times we don't need to set all the values a shorthand property represents. For example, HTML headings only set top and bottom margin, so when necessary, only override those two values. Excessive use of shorthand properties often leads to sloppier code with unnecessary overrides and unintended side effects.
267 |
The Mozilla Developer Network has a great article on shorthand properties for those unfamiliar with notation and behavior.
Avoid unnecessary nesting. Just because you can nest, doesn't mean you always should. Consider nesting only if you must scope styles to a parent and if there are multiple elements to be nested.
Code is written and maintained by people. Ensure your code is descriptive, well commented, and approachable by others. Great code comments convey context or purpose. Do not simply reiterate a component or class name.
288 |
Be sure to write in complete sentences or larger comments and succinct phrases for general notes.
Set your editor to the following settings to avoid common code inconsistencies and dirty diffs:
351 |
352 |
Use soft-tabs set to two spaces.
353 |
Trim trailing white space on save.
354 |
Set encoding to UTF-8.
355 |
Add new line at end of files.
356 |
357 |
Consider documenting and applying these preferences to your project's .editorconfig file. For an example, see the one in Bootstrap. Learn more about EditorConfig.