Chromium Web Development Style Guide
December 5, 2019 · View on GitHub
Chromium Web Development Style Guide
[TOC]
Where does this style guide apply?
This style guide targets Chromium frontend features implemented with JavaScript, CSS, and HTML. Developers of these features should adhere to the following rules where possible, just like those using C++ conform to the Chromium C++ styleguide.
This guide follows and builds on:
Separation of presentation and content
When designing a feature with web technologies, separate the:
- content you are presenting to the user (HTML)
- styling of the data (CSS)
- logic that controls the dynamic behavior of the content and presentation (JS)
This highlights the concern of each part of the code and promotes looser coupling (which makes refactor easier down the road).
Another way to envision this principle is using the MVC pattern:
| MVC Component | Web Component |
|---|---|
| Model | HTML |
| View | CSS |
| Controller | JS |
It's also often appropriate to separate each implementation into separate files.
DO:
<!-- missile-button.html -->
<link rel="stylesheet" href="warnings.css">
<b class="warning">LAUNCH BUTTON WARNING</b>
<script src="missile-button.js">
/* warnings.css */
.warning {
color: red;
}
// missile-button.js
document.querySelector('b').onclick = fireZeeMissiles;
DON'T:
<!-- missile-button.html -->
<b style="color: red;" onclick="fireZeeMissiles()">LAUNCH BUTTON WARNING</span>
on-event-style event listener wiring and
<style> tags that live inside of .html files.
HTML
See the Google HTML/CSS Style guide.
Head
<!doctype html>
<html dir="$i18n{direction}">
<head>
<meta charset="utf-8">
<title>$i18n{myFeatureTitle}</title>
<link rel="icon" href="feature.png">
<link rel="stylesheet" href="feature.css">
<script src="feature.js"></script>
</head>
…
</html>
-
Specify
<!doctype html>. -
Set the
dirattribute of the html element to the localized ‘textdirection’ value. This flips the page visually for RTL languages and allowshtml[dir=rtl]selectors to work. -
Specify the charset, UTF-8.
-
Link in image, icon and stylesheet resources.
- Do not style elements with
style="..."attributes.
- Do not style elements with
-
Include the appropriate JS scripts.
- Do not add JS to element event handlers.
on-click are allowed and often reduce
the amount of addressing (adding an ID just to wire up event handling).
Body
<h3>$i18n{autofillAddresses}</h3>
<div class="settings-list">
<list id="address-list"></list>
<div>
<button id="autofill-add-address">$i18n{autofillAddAddress}</button>
</div>
</div>
<if expr="chromeos">
<a href="https://www.google.com/support/chromeos/bin/answer.py?answer=142893"
target="_blank">$i18n{learnMore}</a>
</if>
-
Element IDs use
dash-form- Exception:
camelCaseis allowed in Polymer code for easierthis.$.idNameaccess.
- Exception:
-
Localize all strings using $i18n{}
-
Use camelCase for $i18n{} keys names.
-
Add 2 space indentation in each new block.
-
Adhere to the 80-column limit.
- Indent 4 spaces when wrapping a previous line.
-
Use double-quotes instead of single-quotes for all attributes.
-
Don't close single tags
- DO:
<input type="radio"> - DON'T:
<input type="radio" />
- DO:
<custom-elements> and some HTML elements like
<iframe> require closing.
-
Use the
buttonelement instead of<input type="button">. -
Do not use
<br>; place blocking elements (<div>) as appropriate. -
Do not use spacing-only divs; set the margins on the surrounding elements.
-
Only use
<table>elements when displaying tabular data. -
Do not use the
forattribute of<label>- If you're labelling a checkbox, put the
<input>inside the<label> - If you're labelling purely for accessibility, e.g. a
<select>, usearia-labelledby
- If you're labelling a checkbox, put the
CSS
See the Google HTML/CSS style guide (and again, browser compatibility issues are less relevant for Chrome-only code).
.raw-button,
.raw-button:hover,
.raw-button:active {
--sky-color: blue;
-webkit-margin-collapse: discard;
background-color: rgb(253, 123, 42);
background-repeat: no-repeat;
border: none;
min-width: 0;
padding: 1px 6px;
}
-
Specify one selector per line.
- Exception: One rule / one line frames in a
@keyframe(see below).
- Exception: One rule / one line frames in a
-
Opening brace on the same line as the last (or only) selector.
-
Two-space indentation for each declaration, one declaration per line, terminated by a semicolon.
-
Use shorthand notation when possible.
-
Alphabetize properties.
-webkitproperties should be listed at the top, sorted alphabetically.--variablesshould be alphabetically declared when possible.
-
Insert a space after the colon separating property and value.
-
Do not create a class for only one element; use the element ID instead.
-
When specifying length values, do not specify units for a zero value, e.g.,
left: 0px;becomesleft: 0;- Exception: 0% values in lists of percentages like
hsl(5, 0%, 90%)or within @keyframe directives, e.g:
- Exception: 0% values in lists of percentages like
@keyframe animation-name {
0% { /* beginning of animation */ }
100% { /* end of animation */ }
}
-
Use single quotes instead of double quotes for all strings.
-
Don't use quotes around
url()s unless needed (i.e. adata:URI). -
Class names use
dash-form. -
If time lengths are less than 1 second, use millisecond granularity.
- DO:
transition: height 200ms; - DON'T:
transition: height 0.2s;
- DO:
-
Use two colons when addressing a pseudo-element (i.e.
::after,::before,::-webkit-scrollbar). -
Use scalable
font-sizeunits like%oremto respect users' default font size -
Don't use CSS Mixins (
--mixin: {}or@apply --mixin;) in new code. We're removing them.- Mixins were dropped from CSS in favor of CSS Shadow Parts.
- Instead, replace CSS mixin usage with one of these natively supported
alternatives:
- CSS Shadow Parts or CSS variables for styling of DOM nodes residing in the Shadow DOM of a child node.
- Plain CSS classes, for grouping a set of styles together for easy reuse.
Color
-
When possible, use named colors (i.e.
white,black) to enhance readability. -
Prefer
rgb()orrgba()with decimal values instead of hex notation (#rrggbb).- Exception: shades of gray (i.e.
#333)
- Exception: shades of gray (i.e.
-
If the hex value is
#rrggbb, use the shorthand notation#rgb.
URLs
- Don't embed data URIs in source files. Instead, use grit's flattening.
background-image: url(../path/to/image.svg);
The contents of file.png are base64-encoded and the url() is replaced with
background-image: url(data:image/svg+xml;base64,...);
if flattenhtml="true" is specified in your .grd file.
RTL
.suboption {
margin-inline-start: 16px;
}
#save-button {
color: #fff;
left: 10px;
}
html[dir='rtl'] #save-button {
right: 10px;
}
Use RTL-friendly versions of things like margin or padding where possible:
margin-left->margin-inline-startpadding-right->padding-inline-endtext-align: left->text-align: starttext-align: right->text-align: end- set both
leftfor[dir='ltr']andrightfor[dir='rtl']
For properties that don't have an RTL-friendly alternatives, use
html[dir='rtl'] as a prefix in your selectors.
JavaScript
Style
See the Google JavaScript Style Guide as well as ECMAScript Features in Chromium.
-
Use
$('element-id')instead ofdocument.getElementById -
Use single-quotes instead of double-quotes for all strings.
clang-formatnow handles this automatically.
-
Use ES5 getters and setters
- Use
@type(instead of@returnor@param) for JSDoc annotations on getters/setters
- Use
-
See Annotating JavaScript for the Closure Compiler for @ directives
-
Prefer
event.preventDefault()toreturn falsefrom event handlers
Closure compiler
-
Use the closure compiler to identify JS type errors and enforce correct JSDoc annotations.
-
Add a
BUILD.gnfile to any new web UI code directory. -
Ensure that your
BUILD.gnfile is included insrc/BUILD.gn:webui_closure_compile(or somewhere in its deps hierarchy) so that your code is typechecked in an automated way. -
Type Polymer elements by appending 'Element' to the element name, e.g.
/** @type {IronIconElement} */ -
Use explicit nullability in JSDoc type information
- Rather than
@type {Object}use:{!Object}for only Object{!Object|undefined}for an Object that may be undefined{?Object}for Object that may be null
- Do the same for typedefs and Array (or any other nullable type)
- Rather than
-
Don't add a
.after template types- DO:
Array<number> - DON'T:
Array.<number>
- DO:
-
Don't specify string in template object types. That's the only type of key
Objectcan possibly have.- DO:
Object<T> - DON'T:
Object<string, T>
- DO:
-
Use template types for any class that supports them, for example:
ArrayCustomEventMapPromiseSet
Polymer
Also see the Google Polymer Style Guide.
-
Use a consistent ordering in the “prototype” object passed to
Polymer():isbehaviorsproperties(public, then private)hostAttributeslisteners,observerscreated,ready,attached,detached- public methods
- event handlers, computed functions, and private methods
-
Use camelCase for element IDs to simplify local DOM accessors (i.e.
this.$.camelCaseinstead ofthis.$[‘dash-case’]). -
Use
this.fooinstead ofnewFooarguments in observers when possible. This makes changing the type ofthis.fooeasier (as the@typeis duplicated in less places, i.e.@param).
properties: {
foo: {type: Number, observer: 'fooChanged_'}
},
/** @private */
fooChanged_: function() {
this.bar = this.derive(this.foo);
},
-
Use native
on-clickfor click events instead ofon-tap. 'tap' is a synthetic event provided by Polymer for backward compatibility with some browsers and is not needed by Chrome. -
Make good use of the
dom-iftemplate:-
Consider using
dom-ifto lazily render parts of the DOM that are hidden by default. Also consider usingcr-lazy-renderinstead. -
Only use
dom-ifif the DOM subtree is non-trivial, defined as:- Contains more than 10 native elements, OR
- Contain any custom elements, OR
- Has many data bindings, OR
- Includes non-text content (e.g images).
For trivial DOM subtrees using the HTML
hiddenattribute yields better performance, than adding a customdom-ifelement.
-
-
Do not add iron-icons dependency to third_party/polymer/.
- Polymer provides icons via the
iron-iconslibrary, but importing each of the iconsets means importing hundreds of SVGs, which is unnecessary because Chrome uses only a small subset. - Alternatives:
- Include the SVG in a WebUI page-specific icon file. e.g.
chrome/browser/resources/settings/icons.html. - If reused across multiple WebUI pages, include the SVG in
ui/webui/resources/cr_elements/icons.html.
- Include the SVG in a WebUI page-specific icon file. e.g.
- You may copy the SVG code from iron-icons files.
- Polymer provides icons via the
Grit processing
Grit is a tool that runs at compile time to pack resources together into Chromium.
Preprocessing
Grit can be used to selectively include or exclude code at compile-time in web
code. Preprocessing is be enabled by adding the preprocess="true" attribute
inside of a .grd file on <structure> and <include> nodes.
<if> tags allow conditional logic by evaluating an expression in a
compile-time environment of grit variables. These allow conditionally include
or excluding code.
Example:
function isWindows() {
// <if expr="win">
return true;
// </if>
return false;
}
<include src="[path]"> reads the file at path and replaces the <include>
tag with the file contents of [path]. Don't use <include> in new JS code;
it is being removed.
Instead, use JS imports in new pages and pages that use JS modules. Use HTML
imports in existing pages that are still using HTML imports/Polymer 2.
Grit can read and inline resources when enabled via flattenhtml="true".
Example:
.spinner {
background: url(../relative/file/path/to/spinner.svg);
}
Is transformed to:
.spinner {
background: url(data:image/svg+xml;... base64-encoded content ...);
}
A minification tool can be specified to Grit (like Closure compiler) to transform the code before it's packed into a bundle.