Appliquez vos règles, concepts et bonnes pratiques ou celles décrites sur cette page. Contribuer à ce Code Guide sur GitHub en créant un ticket
Tout le code doit semblé avoir été écrit par une seule personne, peu importe le nombre de contributeurs.
</li> ou </body>.<!DOCTYPE html>
<html>
<head>
<title>Titre de page</title>
</head>
<body>
<img src="images/company-logo.png" alt="Company">
<h1 class="hello-world">Hello, world!</h1>
</body>
</html>
Utiliser cette simple déclaration de Doctype au début de chaque page HTML permet un rendu optimum sur tous les navigateurs.
<!DOCTYPE html>
<html>
<head>
</head>
</html>
Utilisez ce type d'encodage pour vous assurer le meilleur rendu des charactères.
<head>
<meta charset="UTF-8">
</head>
Tel que décrit dans les spécifications HTML5, il n'est pas nécessaire d'ajouter les attributs type lors de l'inlcusion des CSS et JavaScript. text/css et text/javascript sont les valeurs par défaut.
<!-- External CSS -->
<link rel="stylesheet" href="code-guide.css">
<!-- In-document CSS -->
<style>
/* ... */
</style>
<!-- JavaScript -->
<script src="code-guide.js"></script>
Maintenir la sémantique et les standards HTML oui, mais pas au prix de l'aspect pratique. Utiliser le minimum de balise avec le moins de détail dans la mesure du possible.
Les attributs HTML doivent être ordoné pour une meilleure lecture.
classid, namedata-*src, for, type, hreftitle, altaria-*, roleLes classes sont des composants réutilisable, elles sont donc spécifiées en premier. Viennent ensuite les ids, plus spécifique, ils doivent être utilisés avec parcimonie (par exemple comme navigation interne à la page).
<a class="..." id="..." data-modal="toggle" href="#">
Lien d'exemple
</a>
<input class="form-control" type="text">
<img src="..." alt="...">
Les attributs booléens n'ont pas besoin d'une valeur déclarée. Avec XHTML, chaque attribut nécessitait une valeure. Avec HTML5, ce n'est plus le cas.
Pour plus d'information consultez la section concernant les attributs boolén de WhatWG [en]:
La présence d'un attribut booléen dans un élément indique une valeure vrai, son absence indique une valeure fausse.
Dans le cas ou vous devez inclure la valeur de l'attribut et vous n'avez pas besoin de le faire, suivez les recommendations de WhatWG :
Si l'attribut est présent, sa valeure doit être une chaine de charactère vide ou [...] le nom de l'attribut sans espace.
En résumé, pas de valeur.
<input type="text" disabled>
<input type="checkbox" value="1" checked>
<select>
<option value="1" selected>1</option>
</select>
Lorsque c'est possible, éviter les éléments parents superflus. Écrire moins d'HTML évite les problèmes de maintenance. Comme dans l'exemple suivant :
<!-- Not so great -->
<span class="avatar">
<img src="...">
</span>
<!-- Better -->
<img class="avatar" src="...">
Produire des balises via JavaScript rends le contenu difficile à trouver, à éditer et réduit les performances. Á éviter si possible.
: for each declaration.box-shadow).rgb(), rgba(), hsl(), hsla(), or rect() values. This helps differentiate multiple color values (comma, no space) from multiple property values (comma with space). Also, don't prefix values with a leading zero (e.g., .5 instead of 0.5).#fff. Lowercase letters are much easier to discern when scanning a document as they tend to have more unique shapes.#fff instead of #ffffff.input[type="text"]. They’re only optional in some cases, and it’s a good practice for consistency.margin: 0; instead of margin: 0px;.Questions on the terms used here? See the syntax section of the Cascading Style Sheets article on Wikipedia.
/* Bad CSS */
.selector, .selector-secondary, .selector[type=text] {
padding:15px;
margin:0px 0px 15px;
background-color:rgba(0, 0, 0, 0.5);
box-shadow:0 1px 2px #CCC,inset 0 1px 0 #FFFFFF
}
/* Good CSS */
.selector,
.selector-secondary,
.selector[type="text"] {
padding: 15px;
margin: 0 0 15px;
background-color: rgba(0,0,0,.5);
box-shadow: 0 1px 2px #ccc, inset 0 1px 0 #fff;
}
Related property declarations should be grouped together following the order:
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.
Everything else takes place inside the component or without impacting the previous two sections, and thus they come last.
For a complete list of properties and their order, please see Recess.
.declaration-order {
/* Positioning */
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 100;
/* Box-model */
display: block;
float: right;
width: 100px;
height: 100px;
/* Typography */
font: normal 13px "Helvetica Neue", sans-serif;
line-height: 1.5;
color: #333;
text-align: center;
/* Visual */
background-color: #f5f5f5;
border: 1px solid #e5e5e5;
border-radius: 3px;
/* Misc */
opacity: 1;
}
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.
.element { ... }
.element-avatar { ... }
.element-selected { ... }
@media (min-width: 480px) {
.element { ...}
.element-avatar { ... }
.element-selected { ... }
}
When using vendor prefixed properties, indent each property such that the declaration's value lines up vertically for easy multi-line editing.
In Textmate, use Text → Edit Each Line in Selection (⌃⌘A). In Sublime Text 2, use Selection → Add Previous Line (⌃⇧↑) and Selection → Add Next Line (⌃⇧↓).
/* Prefixed properties */
.selector {
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.15);
box-shadow: 0 1px 2px rgba(0,0,0,.15);
}
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.
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.
/* Single declarations on one line */
.span1 { width: 60px; }
.span2 { width: 140px; }
.span3 { width: 220px; }
/* Multiple declarations, one per line */
.sprite {
display: inline-block;
width: 16px;
height: 15px;
background-image: url(../img/sprite.png);
}
.icon { background-position: 0 0; }
.icon-home { background-position: 0 -20px; }
.icon-account { background-position: 0 -40px; }
Strive to limit use of shorthand declarations to instances where you must explicitly set all the available values. Common overused shorthand properties include:
paddingmarginfontbackgroundborderborder-radiusOften 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.
The Mozilla Developer Network has a great article on shorthand properties for those unfamiliar with notation and behavior.
/* Bad example */
.element {
margin: 0 0 10px;
background: red;
background: url("image.jpg");
border-radius: 3px 3px 0 0;
}
/* Good example */
.element {
margin-bottom: 10px;
background-color: red;
background-image: url("image.jpg");
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
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.
// Without nesting
.table > thead > tr > th { … }
.table > thead > tr > td { … }
// With nesting
.table > thead > tr {
> th { … }
> td { … }
}
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.
Be sure to write in complete sentences for larger comments and succinct phrases for general notes.
/* Bad example */
/* Modal header */
.modal-header {
...
}
/* Good example */
/* Wrapping element for .modal-title and .modal-close */
.modal-header {
...
}
.btn and .btn-danger)..btn is useful for button, but .s doesn't mean anything..js-* classes to denote behavior (as opposed to style), but keep these classes out of your CSS./* Bad example */
.t { ... }
.red { ... }
.header { ... }
/* Good example */
.tweet { ... }
.important { ... }
.tweet-header { ... }
[class^="..."]) on commonly occuring components. Browser performance is known to be impacted by these.Additional reading:
/* Bad example */
span { ... }
.page-container #stream .stream-item .tweet .tweet-header .username { ... }
.avatar { ... }
/* Good example */
.avatar { ... }
.tweet-header .username { ... }
.tweet .avatar { ... }
/*
* Component section heading
*/
.element { ... }
/*
* Component section heading
*
* Sometimes you need to include optional context for the entire component. Do that up here if it's important enough.
*/
.element { ... }
/* Contextual sub-component or modifer */
.element-heading { ... }
Set your editor to the following settings to avoid common code inconsistencies and dirty diffs:
Consider documenting and applying these preferences to your project's .editorconfig file. For an example, see the one in Bootstrap. Learn more about EditorConfig.