Movatterモバイル変換


[0]ホーム

URL:


Google HTML/CSS Style Guide

Background

This document defines formatting and style rules for HTML and CSS. It aims atimproving collaboration, code quality, and enabling supporting infrastructure.It applies to raw, working files that use HTML and CSS, including Sass and GSSfiles. Tools are free to obfuscate, minify, and compile as long as the generalcode quality is maintained.

General

General Style Rules

Protocol

Use HTTPS for embedded resources where possible.

Always use HTTPS (https:) for images and other media files, style sheets, andscripts, unless the respective files are not available over HTTPS.

<!-- Not recommended: omits the protocol --><script src="//ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script><!-- Not recommended: uses HTTP --><script src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<!-- Recommended --><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
/* Not recommended: omits the protocol */@import '//fonts.googleapis.com/css?family=Open+Sans';/* Not recommended: uses HTTP */@import 'http://fonts.googleapis.com/css?family=Open+Sans';
/* Recommended */@import 'https://fonts.googleapis.com/css?family=Open+Sans';

General Formatting Rules

Indentation

Indent by 2 spaces at a time.

Don’t use tabs or mix tabs and spaces for indentation.

<ul>  <li>Fantastic  <li>Great</ul>
.example {  color: blue;}

Capitalization

Use only lowercase.

All code has to be lowercase: This applies to HTML element names, attributes,attribute values (unlesstext/CDATA), CSS selectors, properties, and propertyvalues (with the exception of strings).

<!-- Not recommended --><A HREF="/">Home</A>
<!-- Recommended --><img src="google.png" alt="Google">
/* Not recommended */color: #E5E5E5;
/* Recommended */color: #e5e5e5;

Trailing Whitespace

Remove trailing white spaces.

Trailing white spaces are unnecessary and can complicate diffs.

<!-- Not recommended --><p>What?_
<!-- Recommended --><p>Yes please.

General Meta Rules

Encoding

Use UTF-8 (no BOM).

Make sure your editor uses UTF-8 as character encoding, without a byte ordermark.

Specify the encoding in HTML templates and documents via<metacharset="utf-8">. Do not specify the encoding of style sheets as these assumeUTF-8.

(More on encodings and when and how to specify them can be found inHandling character encodings in HTML and CSS.)

Comments

Explain code as needed, where possible.

Use comments to explain code: What does it cover, what purpose does it serve,why is respective solution used or preferred?

(This item is optional as it is not deemed a realistic expectation to alwaysdemand fully documented code. Mileage may vary heavily for HTML and CSS code anddepends on the project’s complexity.)

Action Items

Mark todos and action items withTODO.

Highlight todos by using the keywordTODO only, not other common formats like@@.

Append action items after a colon as inTODO: actionitem.

{# TODO: Revisit centering. #}<center>Test</center>
<!-- TODO: Remove optional tags. --><ul>  <li>Apples</li>  <li>Oranges</li></ul>

HTML

HTML Style Rules

Document Type

Use<!doctype html>.

Always put your HTML inno-quirks modeby including<!doctype html> at the beginning of the document.

A document without a doctype is rendered in “quirks mode”, and one with adifferent doctype may be rendered in “limited-quirks mode”. These modes don’tfollow the widely-understood, widely-documented behavior for various core HTMLand CSS constructs, and are likely to cause subtle failures andincompatibilities especially when re-using code that expects no-quirks mode.

HTML Validity

Use valid HTML where possible.

Use valid HTML code unless that is not possible due to otherwise unattainableperformance goals regarding file size.

Use tools such as theW3C HTML validatorto test.

Using valid HTML is a measurable baseline quality attribute that contributes tolearning about technical requirements and constraints, and that ensures properHTML usage.

<!-- Not recommended --><title>Test</title><article>This is only a test.
<!-- Recommended --><!doctype html><meta charset="utf-8"><title>Test</title><article>This is only a test.</article>

Semantics

Use HTML according to its purpose.

Use elements (sometimes incorrectly called “tags”) for what they have beencreated for. For example, use heading elements for headings,p elements forparagraphs,a elements for anchors, etc.

Using HTML according to its purpose is important for accessibility, reuse, andcode efficiency reasons.

<!-- Not recommended --><div>All recommendations</div>
<!-- Recommended --><a href="recommendations/">All recommendations</a>

Multimedia Fallback

Provide alternative contents for multimedia.

For multimedia, such as images, videos, animated objects viacanvas, make sureto offer alternative access. For images that means use of meaningful alternativetext (alt) and for video and audio transcripts and captions, if available.

Providing alternative contents is important for accessibility reasons: A blinduser has few cues to tell what an image is about without@alt, and other usersmay have no way of understanding what video or audio contents are about either.

(For images whosealt attributes would introduce redundancy, and for imageswhose purpose is purely decorative which you cannot immediately use CSS for, useno alternative text, as inalt="".)

<!-- Not recommended --><img src="spreadsheet.png">
<!-- Recommended --><img src="spreadsheet.png" alt="Spreadsheet screenshot.">

Separation of Concerns

Separate structure from presentation from behavior.

Strictly keep structure (markup), presentation (styling), and behavior(scripting) apart, and try to keep the interaction between the three to anabsolute minimum.

That is, make sure documents and templates contain only HTML and HTML that issolely serving structural purposes. Move everything presentational into stylesheets, and everything behavioral into scripts.

In addition, keep the contact area as small as possible by linking as few stylesheets and scripts as possible from documents and templates.

Separating structure from presentation from behavior is important formaintenance reasons. It is always more expensive to change HTML documents andtemplates than it is to update style sheets and scripts.

<!-- Not recommended --><!doctype html><title>HTML sucks</title><link rel="stylesheet" href="base.css" media="screen"><link rel="stylesheet" href="grid.css" media="screen"><link rel="stylesheet" href="print.css" media="print"><h1>HTML sucks</h1><p>I’ve read about this on a few sites but now I’m sure:  <u>HTML is stupid!!1</u><center>I can’t believe there’s no way to control the styling of  my website without doing everything all over again!</center>
<!-- Recommended --><!doctype html><title>My first CSS-only redesign</title><link rel="stylesheet" href="default.css"><h1>My first CSS-only redesign</h1><p>I’ve read about this on a few sites but today I’m actually  doing it: separating concerns and avoiding anything in the HTML of  my website that is presentational.<p>It’s awesome!

Entity References

Do not use entity references.

There is no need to use entity references like&mdash;,&rdquo;, or&#x263a;, assuming the same encoding (UTF-8) is used for files and editors aswell as among teams.

The only exceptions apply to characters with special meaning in HTML (like<and&) as well as control or “invisible” characters (like no-break spaces).

<!-- Not recommended -->The currency symbol for the Euro is &ldquo;&eur;&rdquo;.
<!-- Recommended -->The currency symbol for the Euro is “€”.

Optional Tags

Omit optional tags (optional).

For file size optimization and scannability purposes, consider omitting optionaltags. TheHTML5 specificationdefines what tags can be omitted.

(This approach may require a grace period to be established as a wider guidelineas it’s significantly different from what web developers are typically taught.For consistency and simplicity reasons it’s best served omitting all optionaltags, not just a selection.)

<!-- Not recommended --><!doctype html><html>  <head>    <title>Spending money, spending bytes</title>  </head>  <body>    <p>Sic.</p>  </body></html>
<!-- Recommended --><!doctype html><title>Saving money, saving bytes</title><p>Qed.

type Attributes

Omittype attributes for style sheets and scripts.

Do not usetype attributes for style sheets (unless not using CSS) and scripts(unless not using JavaScript).

Specifyingtype attributes in these contexts is not necessary as HTML5 impliestext/cssandtext/javascriptas defaults. This can be safely done even for older browsers.

<!-- Not recommended --><link rel="stylesheet" href="https://www.google.com/css/maia.css"    type="text/css">
<!-- Recommended --><link rel="stylesheet" href="https://www.google.com/css/maia.css">
<!-- Not recommended --><script src="https://www.google.com/js/gweb/analytics/autotrack.js"    type="text/javascript"></script>
<!-- Recommended --><script src="https://www.google.com/js/gweb/analytics/autotrack.js"></script>

id Attributes

Avoid unnecessaryid attributes.

Preferclass attributes for styling anddata attributes for scripting.

Whereid attributes are strictly required, always include a hyphen in thevalue to ensure it does not match the JavaScript identifier syntax, e.g. useuser-profile rather than justprofile oruserProfile.

When an element has anid attribute, browsers will make that available as anamed property on the globalwindow prototype,which may cause unexpected behavior. Whileid attribute values containing ahyphen are still available as property names, these cannot be referenced asglobal JavaScript variables.

<!-- Not recommended: `window.userProfile` will resolve to reference the <div> node --><div></div>
<!-- Recommended: `id` attribute is required and its value includes a hyphen --><div aria-describedby="user-profile">  …  <div></div>  …</div>

HTML Formatting Rules

General Formatting

Use a new line for every block, list, or table element, and indent every suchchild element.

Independent of the styling of an element (as CSS allows elements to assume adifferent role perdisplay property), put every block, list, or table elementon a new line.

Also, indent them if they are child elements of a block, list, or table element.

(If you run into issues around whitespace between list items it’s acceptable toput allli elements in one line. A linter is encouraged to throw a warninginstead of an error.)

<blockquote>  <p><em>Space</em>, the final frontier.</p></blockquote>
<ul>  <li>Moe  <li>Larry  <li>Curly</ul>
<table>  <thead>    <tr>      <th scope="col">Income      <th scope="col">Taxes  <tbody>    <tr>      <td>$ 5.00      <td>$ 4.50</table>

HTML Line-Wrapping

Break long lines (optional).

While there is no column limit recommendation for HTML, you may considerwrapping long lines if it significantly improves readability.

When line-wrapping, each continuation line should be indented to distinguishwrapped attributes from child elements. Lines should be wrapped consistentlywithin a project, ideally enforced by automated code formatting tools.

<button  mat-icon-button  color="primary"   (click)="openMenu()">  <mat-icon>menu</mat-icon></button>
<button mat-icon-button color="primary"    (click)="openMenu()">  <mat-icon>menu</mat-icon></button>
<button    mat-icon-button    color="primary"       (click)="openMenu()">  <mat-icon>menu</mat-icon></button>
<button mat-icon-button        color="primary"               (click)="openMenu()">  <mat-icon>menu</mat-icon></button>

HTML Quotation Marks

When quoting attributes values, use double quotation marks.

Use double ("") rather than single quotation marks ('') around attributevalues.

<!-- Not recommended --><a class='maia-button maia-button-secondary'>Sign in</a>
<!-- Recommended --><a>Sign in</a>

CSS

CSS Style Rules

CSS Validity

Use valid CSS where possible.

Unless dealing with CSS validator bugs or requiring proprietary syntax, usevalid CSS code.

Use tools such as theW3C CSS validatorto test.

Using valid CSS is a measurable baseline quality attribute that allows to spotCSS code that may not have any effect and can be removed, and that ensuresproper CSS usage.

Class Naming

Use meaningful or generic class names.

Instead of presentational or cryptic names, always use class names that reflectthe purpose of the element in question, or that are otherwise generic.

Names that are specific and reflect the purpose of the element should bepreferred as these are most understandable and the least likely to change.

Generic names are simply a fallback for elements that have no particular or nomeaning different from their siblings. They are typically needed as “helpers.”

Using functional or generic names reduces the probability of unnecessarydocument or template changes.

/* Not recommended: meaningless */.yee-1901 {}/* Not recommended: presentational */.button-green {}.clear {}
/* Recommended: specific */.gallery {}.login {}.video {}/* Recommended: generic */.aux {}.alt {}

Class Name Style

Use class names that are as short as possible but as long as necessary.

Try to convey what a class is about while being as brief as possible.

Using class names this way contributes to acceptable levels of understandabilityand code efficiency.

/* Not recommended */.navigation {}.atr {}
/* Recommended */.nav {}.author {}

Class Name Delimiters

Separate words in class names by a hyphen.

Do not concatenate words and abbreviations in selectors by any characters(including none at all) other than hyphens, in order to improve understandingand scannability.

/* Not recommended: does not separate the words “demo” and “image” */.demoimage {}/* Not recommended: uses underscore instead of hyphen */.error_status {}
/* Recommended */.video-id {}.ads-sample {}

Prefixes

Prefix selectors with an application-specific prefix (optional).

In large projects as well as for code that gets embedded in other projects or onexternal sites use prefixes (as namespaces) for class names. Use short, uniqueidentifiers followed by a dash.

Using namespaces helps preventing naming conflicts and can make maintenanceeasier, for example in search and replace operations.

.adw-help {} /* AdWords */.maia-note {} /* Maia */

Type Selectors

Avoid qualifying class names with type selectors.

Unless necessary (for example with helper classes), do not use element names inconjunction with classes.

Avoiding unnecessary ancestor selectors is useful forperformance reasons.

/* Not recommended */ul.example {}div.error {}
/* Recommended */.example {}.error {}

ID Selectors

Avoid ID selectors.

ID attributes are expected to be unique across an entire page, which isdifficult to guarantee when a page contains many components worked on by manydifferent engineers. Class selectors should be preferred in all situations.

/* Not recommended */#example {}
/* Recommended */.example {}

Shorthand Properties

Use shorthand properties where possible.

CSS offers a variety ofshorthandproperties (likefont) that should be used whenever possible, even in caseswhere only one value is explicitly set.

Using shorthand properties is useful for code efficiency and understandability.

/* Not recommended */border-top-style: none;font-family: palatino, georgia, serif;font-size: 100%;line-height: 1.6;padding-bottom: 2em;padding-left: 1em;padding-right: 1em;padding-top: 0;
/* Recommended */border-top: 0;font: 100%/1.6 palatino, georgia, serif;padding: 0 1em 2em;

0 and Units

Omit unit specification after “0” values, unless required.

Do not use units after0 values unless they are required.

flex: 0px; /* This flex-basis component requires a unit. */flex: 1 1 0px; /* Not ambiguous without the unit, but needed in IE11. */margin: 0;padding: 0;

Leading 0s

Always include leading “0”s in values.

Put0s in front of values or lengths between -1 and 1.

font-size: 0.8em;

Hexadecimal Notation

Use 3 character hexadecimal notation where possible.

For color values that permit it, 3 character hexadecimal notation is shorter andmore succinct.

/* Not recommended */color: #eebbcc;
/* Recommended */color: #ebc;

Important Declarations

Avoid using!important declarations.

These declarations break the natural cascade of CSS and make it difficult toreason about and compose styles. Useselector specificityto override properties instead.

/* Not recommended */.example {  font-weight: bold !important;}
/* Recommended */.example {  font-weight: bold;}

Hacks

Avoid user agent detection as well as CSS “hacks”—try a different approachfirst.

It’s tempting to address styling differences over user agent detection orspecial CSS filters, workarounds, and hacks. Both approaches should beconsidered last resort in order to achieve and maintain an efficient andmanageable code base. Put another way, giving detection and hacks a free passwill hurt projects in the long run as projects tend to take the way of leastresistance. That is, allowing and making it easy to use detection and hacksmeans using detection and hacks more frequently—and more frequently is toofrequently.

CSS Formatting Rules

Declaration Order

Alphabetize declarations (optional).

Sort declarations consistently within a project. In the absence of tooling toautomate and enforce a consistent sort order, consider putting declarations inalphabetical order in order to achieve consistent code in a way that is easy tolearn, remember, and manually maintain.

Ignore vendor-specific prefixes for sorting purposes. However, multiplevendor-specific prefixes for a certain CSS property should be kept sorted (e.g.-moz prefix comes before -webkit).

background: fuchsia;border: 1px solid;-moz-border-radius: 4px;-webkit-border-radius: 4px;border-radius: 4px;color: black;text-align: center;text-indent: 2em;

Block Content Indentation

Indent all block content.

Indent allblock content,that is rules within rules as well as declarations, so to reflect hierarchy andimprove understanding.

@media screen, projection {  html {    background: #fff;    color: #444;  }}

Declaration Stops

Use a semicolon after every declaration.

End every declaration with a semicolon for consistency and extensibilityreasons.

/* Not recommended */.test {  display: block;  height: 100px}
/* Recommended */.test {  display: block;  height: 100px;}

Property Name Stops

Use a space after a property name’s colon.

Always use a single space between property and value (but no space betweenproperty and colon) for consistency reasons.

/* Not recommended */h3 {  font-weight:bold;}
/* Recommended */h3 {  font-weight: bold;}

Declaration Block Separation

Use a space between the last selector and the declaration block.

Always use a single space between the last selector and the opening brace thatbegins thedeclaration block.

The opening brace should be on the same line as the last selector in a givenrule.

/* Not recommended: missing space */.video{  margin-top: 1em;}/* Not recommended: unnecessary line break */.video{  margin-top: 1em;}
/* Recommended */.video {  margin-top: 1em;}

Selector and Declaration Separation

Separate selectors and declarations by new lines.

Always start a new line for each selector and declaration.

/* Not recommended */a:focus, a:active {  position: relative; top: 1px;}
/* Recommended */h1,h2,h3 {  font-weight: normal;  line-height: 1.2;}

Rule Separation

Separate rules by new lines.

Always put a blank line (two line breaks) between rules.

html {  background: #fff;}body {  margin: auto;  width: 50%;}

CSS Quotation Marks

Use single ('') rather than double ("") quotation marks for attributeselectors and property values.

Do not use quotation marks in URI values (url()).

Exception: If you do need to use the@charset rule, use double quotationmarks—single quotation marks are not permitted.

/* Not recommended */@import url("https://www.google.com/css/maia.css");html {  font-family: "open sans", arial, sans-serif;}
/* Recommended */@import url(https://www.google.com/css/maia.css);html {  font-family: 'open sans', arial, sans-serif;}

CSS Meta Rules

Section Comments

Group sections by a section comment (optional).

If possible, group style sheet sections together by using comments. Separatesections with new lines.

/* Header */.adw-header {}/* Footer */.adw-footer {}/* Gallery */.adw-gallery {}

Parting Words

Be consistent.

If you’re editing code, take a few minutes to look at the code around you anddetermine its style. If they use spaces around all their arithmetic operators,you should too. If their comments have little boxes of hash marks around them,make your comments have little boxes of hash marks around them too.

The point of having style guidelines is to have a common vocabulary of coding sopeople can concentrate on what you’re saying rather than on how you’re sayingit. We present global style rules here so people know the vocabulary, but localstyle is also important. If code you add to a file looks drastically differentfrom the existing code around it, it throws readers out of their rhythm whenthey go to read it. Avoid this.


[8]ページ先頭

©2009-2025 Movatter.jp