1. The background

This document defines several code styles and coding guidelines for writing HTML and CSS. The goal of this article is to improve code quality and teamwork, and to make it infrastructure-enabled, which applies to native HTML, CSS, and even GSS files. And as long as the code quality is maintainable, the code can be obfuscated, compressed, or merged just fine with the tools.

Google HTML/CSS Style Guide

2. The general

2.1 General style rules

2.1.1 agreement

Embedded resource references use the HTTPS protocol whenever possible

Always use HTTPS to reference images and other media files, stylesheets, or script files, unless the target file does not support HTTPS references.

HTML sample

<! -- Not recommended: omit protocol -->
<script src="/ / ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

<! -- Not recommended: use HTTP -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

<! Recommend -- -- -- >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
Copy the code

CSS example

/* not recommended */
@import '//fonts.googleapis.com/css?family=Open+Sans';

/* not recommended */
@import 'http://fonts.googleapis.com/css?family=Open+Sans';

Recommend * / / *
@import 'https://fonts.googleapis.com/css?family=Open+Sans';
Copy the code

2.2 General format rules

2.2.1 the indentation

The indentation is set to 2 Spaces at a time.

Don’t mix TAB and space.

2.2.2 case

All code in the following ranges must be lowercase:

  • HTMLTag and its attributes, attribute values (unless text orCDATA)
  • CSSSelectors with their genera and attribute values (except strings)

The following is an example:

HTML sample

<! -- Not recommended -->
<A HREF="/">Home</A>

<! Recommend -- -- -- >
<img src="google.png" alt="Google">
Copy the code

CSS example

/* not recommended */
color: #E5E5E5;

Recommend * / / *
color: #e5e5e5;
Copy the code

2.2.3 Closing Space

Unnecessary white space characters at the end of each line should be removed.

<! -- Not recommended -->
<p>What? _<! Recommend -- -- -- >
<p>Yes please.
Copy the code

2.3 Metadata Rules

2.3.1 coding

Use UTF-8 encoding without BOM, and make sure your editor uses UTF-8 encoding without byte-order markup.

For more information about encoding and how to specify it, see Character Sets & Encodings in XHTML, HTML and CSS.

Specify encoding in HTML templates and files
There is no need to specify encoding for the stylesheet, which defaults to UTF-8.

2.3.2 annotation

Add comments as informative as possible.

This rule is optional, and there is no need to add sufficient comments everywhere, which can make the overall code less concise, depending on the complexity of the project.

Annotate code: What is this? What is its purpose? What are the respective solutions and which is preferred?

2.3.3 action item

Use the TODO flag to mark tasks or action items.

Use the keyword TODO and highlight the keyword, or use another comment format such as @@ to add the task content or item description (enclosed in parentheses). Item description can be added after colon:

{# TODO(john.doe): revisit centering #}
<center>Test</center>

<! --TODO: remove optional tags -->
<ul>
  <li>Apples</li>
  <li>Oranges</li>
</ul>
Copy the code

3. HTMl

3.1 HTML Style Guide

3.1.1 Document Type

Use it.

It is recommended to write all HTML documents using HTML5 syntax:
.

Text/HTML HTML is recommended. Do not use XHTML, the media type is Application/XHTML + XML, which is not supported by very few browsers and requires more storage)

With HTML, you don’t have to write closing tags for empty elements, such as:

, not

.

3.1.2 HTML validity

Use efficient HTML code whenever possible, unless you have strict performance goals for file sizes that force you to cut back.

Use a tool such as W3C HTML Validator for testing.

Using effective HTML is a measurable baseline of code quality to understand its technical requirements and constraints, and to ensure proper use of HTML.

<! -- Not recommended -->
<title>Test</title>
<article>This is only a test.
    
<! Recommend -- -- -- >
<! DOCTYPEhtml>
<meta charset="utf-8">
<title>Test</title>
<article>This is only a test.</article>
Copy the code

3.1.3 semantic

Use elements (sometimes called “tags”) for what they have been created for.

Use HTML elements (sometimes incorrectly called tags) for the purpose they are designed for. For example, use heading elements H1 to H6 to show headings, p elements to show paragraphs, A elements to show hyperlinks, and so on.

Presenting data according to the purpose for which HTML elements are designed improves accessibility, reusability, and code quality.

<! -- Not recommended -->
<div onclick="goToRecommendations();">All recommendations</div>

<! Recommend -- -- -- >
<a href="recommendations/">All recommendations</a>
Copy the code

3.1.4 Multimedia alternatives

Provide alternatives for multimedia.

For multimedia, such as images, videos, and Canvas animations, make sure to provide alternative content.

For images, you should provide valid and unambiguous Alt attribute values. For audio and video, valid copies and copy instructions should be provided.

It is important to provide alternative solutions. For example, blind people can understand the relevant content of the picture through the Alt attribute value of the picture, and minority users who cannot understand the audio and video content can understand the audio and video content according to their copywriting.

(The Alt attribute of the image is redundant. If you use the image for pure decoration, you can write Alt =””.)

<! -- Not recommended -->
<img src="spreadsheet.png">

<! Recommend -- -- -- >
<img src="spreadsheet.png" alt="Spreadsheet screenshot.">
Copy the code

3.1.5 Separation of concerns

Separate structure, performance and behavior.

Keep structure (HTML), presentation (CSS), and behavior (Javascript) strictly separate, and try to keep interactions between the three to a minimum. Make sure your documents and templates contain only HTML structure, put all presentation in stylesheets, and all behavior in Javascript scripts.

Also, keep external links to a minimum and the style and script interface in the document as small as possible.

Maintaining presentation and behavior separately reduces the cost of changing HTML document structure and templates.

<! -- Not recommended -->
<! DOCTYPEhtml>
<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 style="font-size: 1em;">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>
    
<! Recommend -- -- -- >
<! DOCTYPEhtml>
<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>
<p>It’s awesome!</p>
Copy the code

3.1.6 Entity Characters

Do not overuse entity characters

I’m confused about this, because entity characters have obvious advantages

There is no need to use things like: — , ” , or ☺ Entity characters, although the team uses a consistent editor encoding (UTF-8).

Exceptions for characters with special meaning in HTML documents (such as < and &) and “invisible” characters (such as no-break Spaces).

<! -- Not recommended -->The euro currency symbol is&ldquo;&eur;&rdquo;.<! Recommend -- -- -- >The euro currency symbol is €.Copy the code

3.1.7 Optional Labels

Omit optional labels (optional).

I support the need to keep optional labels

If you want to optimize file size and validation, consider omitting optional tags. Refer to the HTML5 Specification for optional tags.

(This approach may need to be guided by more explicit rules, but many developers have different views, and for reasons of consistency and brevity, it is best to omit optional labels altogether.)

<! -- Not recommended -->
<! DOCTYPEhtml>
<html>
  <head>
    <title>Spending money, spending bytes</title>
  </head>
  <body>
    <p>Sic.</p>
  </body>
</html>
<! Recommend -- -- -- >
<! DOCTYPEhtml>
<title>Saving money, saving bytes</title>
<p>Qed.
Copy the code

3.1.8 typeattribute

Omit the Type attribute when importing stylesheets and scripts.

Do not add the Type attribute to the tags of stylesheets (unless CSS is not used) and scripts (unless JavaScript is not applicable).

There is no need to specify a type attribute value of text/ CSS or text/javascript, which is supported by default in both HTML5 and older browsers.

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

3.2 HTML format rules

3.2.1 General Format

Each block-level element, list contingent table element has a single row, and each child element is indented.

The standalone element style places block-level elements, list elements, and table elements in a new row, or indents them if they are children of a block-level element, list, or table.

(If you have a scenario where the list item has blank nodes around it, try putting all the LI elements on a single line. Some formatting tools use alarms instead of error messages.

<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>The $5.00<td>The $4.50</table>
Copy the code

3.2.2 HTML line

Long single line newline (optional).

If you don’t limit the length of a line, consider wrapping too long a single line for readability. If line breaks, add at least four additional Spaces as indentation to the line break portion.

<md-progress-circular md-mode="indeterminate" class="md-accent"
    ng-show="ctrl.loading" md-diameter="35">
</md-progress-circular>

<md-progress-circular
    md-mode="indeterminate"
    class="md-accent"
    ng-show="ctrl.loading"
    md-diameter="35">
</md-progress-circular>

<md-progress-circular md-mode="indeterminate"
                      class="md-accent"
                      ng-show="ctrl.loading"
                      md-diameter="35">
</md-progress-circular>
Copy the code

3.2.3 HTML quotes

HTML attribute values are always in double quotes.

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

<! Recommend -- -- -- >
<a class="maia-button maia-button-secondary">Sign in</a>
Copy the code

4. CSS

4.1 CSS style rules

4.1.1 CSS Validity

Use effective CSS styles whenever possible.

Unless the CSS validator is buggy or has special syntax, write effective CSS code.

Use a tool like the W3C CSS Validator to test validity.

Using effective CSS is a measurable baseline quality attribute, and if you find some CSS code that doesn’t matter whether it exists or not, you can remove it while ensuring that the CSS usage is correct.

4.1.2 ID and Class Naming

Use a meaningful or generic ID or class name.

Keep id and class names purposeful or generic, and never use names that are intuitively useful or mysterious.

Names reflect the purpose or specificity of elements, which are preferred because they are easy to understand and change.

Common names are simply alternative names for elements that have no specific meaning, such as helpers.

Using functional or generic names can reduce unnecessary document changes.

/* not recommended: nonsense is not easy to understand */
#yee-1901 {}

/* not recommended: the expression is not specific */
.button-green {}
.clear {}
/* Recommended: clear details */
#gallery {}
#login {}
.video {}

/* Recommended: general */
.aux {}
.alt {}
Copy the code

4.1.3 ID and Class naming style

Id and class names should be as short as possible, but longer names can be used if necessary.

Id and class should communicate their purpose and relevance briefly.

Naming ids and classes in this way makes for efficient code and easy to understand.

/* not recommended */
#navigation {}
.atr {}
Recommend * / / *
#nav {}
.author {}
Copy the code

4.1.4 Type selector

Avoid using type selectors to qualify ids and classes.

Do not combine element tag names with IDS or classes unless necessary.

For performance reasons, avoid using parent nodes as selectors.

/* not recommended */
ul#example {}
div.error {}
Recommend * / / *
#example {}
.error {}
Copy the code

4.1.5 Shorthand for Attribute Names

Abbreviate properties and property values whenever possible.

CSS provides a feature (such as font) to abbreviate property values, and developers should use this feature whenever possible to write styles, even if only to explicitly specify a property value.

Using shorthand for attribute names is good for code efficiency and readability.

/* 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;
Copy the code

4.1.6 0 and units

When the attribute value is 0, the unit is omitted unless necessary.

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;
Copy the code

4.1.7 Starting with 0 decimal

Omit the 0 before the decimal point.

Omit the 0 before the decimal point when the value is greater than -1 and less than 1.

font-size:.8em;
Copy the code

4.1.8 Hexadecimal mark

Use three-character hexadecimal tokens whenever possible.

Commonly used when describing color values, 3 string hexadecimal notation is shorter and more concise.

/* not recommended */
color: #eebbcc;
Recommend * / / *
color: #ebc;
Copy the code

4.1.9 prefix

Selectors can optionally be prefixed with a description of the specific functionality of the application.

Id and class can use prefixes (as namespaces) in large projects and in code embedded in other projects or external sites. Prefixes can use short unique identifiers followed by a line.

4.1.10 ID and Class Name Delimiters

Separate terms in ID and class should be linked by – (dash).

Id and class are case insensitive

Do not merge words directly in id and class names, nor should abbreviations be used. Using delimiters improves readability and makes it easier to find.

/* Not recommended: There is no "-" */ between "demo" and "image"
.demoimage {}

/* Not recommended: Use the underscore "_" */
.error_status {}

Recommend * / / *
#video-id {}
.ads-sample {}
Copy the code

4.1.11 Hacks

It is best to avoid CSS Hacks unless all methods have been tried without success.

Hacks can be useful in special situations, but they can make these behaviors too frequent, which can hurt project efficiency and code management in the long run, so look for other solutions whenever possible.

4.2 CSS Formatting rules

4.2.1 Declaration sequence

Declaration in alphabetical order, easy to remember and maintain.

Browser-specific prefix sorting order is ignored, but multi-vendor prefixes should remain relatively sorted (e.g. -moz before -webkit).

Browser prefixes can be handled by tools such as Postcss

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

4.2.2 Indent code block content

All code blocks should be indented.

Indent the content of all code blocks, which improves the clarity of the hierarchy.

@media screen, projection {

  html {
    background: #fff;
    color: # 444; }}Copy the code

4.2.3 Termination of the statement

Add a semicolon after each declaration statement.

Adding semicolons to each declaration improves consistency and extensibility.

/* not recommended */
.test {
  display: block;
  height: 100px
}
Recommend * / / *
.test {
  display: block;
  height: 100px;
}
Copy the code

4.2.4 Attribute Name Termination

Use a space after the attribute name and colon.

Add a space after the attribute name and colon for consistency.

/* not recommended */
h3 {
  font-weight:bold;
}
Recommend * / / *
h3 {
  font-weight: bold;
}
Copy the code

4.2.5 Declare block separation

The last selector and the declaration block are separated by a space.

The opening parenthesis part of the brace should be on the same line as the last selector.

/* Not recommended: missing space */
#video{
  margin-top: 1em;
}

/* Not recommended: selectors and open parentheses are not on the same line */
#video
{
  margin-top: 1em;
}

Recommend * / / *
#video {
  margin-top: 1em;
}
Copy the code

4.2.6 Selector and declaration block separation

Multiple selectors and declaration blocks are not on the same line.

Each selector is on a line.

/* not recommended */
a:focus.a:active {
  position: relative; top: 1px;
}
Recommend * / / *
h1.h2.h3 {
  font-weight: normal;
  line-height: 1.2;
}
Copy the code

4.2.7 Branch of rules

There is a blank line (or two lines) between two rules.

html {
  background: #fff;
}

body {
  margin: auto;
  width: 50%;
}
Copy the code

4.2.8 CSS Quotation marks

Attribute values are marked with single quotes.

Addresses in URL () are not enclosed in quotes.

Exception: If you need to use the @charset rule, use double quotes instead of single quotes.

/* not recommended */
@import url("https://www.google.com/css/maia.css");

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

html {
  font-family: 'open sans', arial, sans-serif;
}
Copy the code

4.3 CSS meta-rules

Comments section 4.3.1

Write comments in groups (optional)

If you can, write comments in groups with a blank line behind them.

/* Header */

#adw-header {}

/* Footer */

#adw-footer {}

/* Gallery */

.adw-gallery {}
Copy the code

Finally want to say

Be consistent.

If you’re going to write code, take a few minutes to look at the original code style and try to keep it consistent.

The point of having a code style guide is to have a common code description style so that people can focus on what you are describing rather than thinking about how you are describing it.

We present these code style rules here so that developers can understand the meaning of consistent code style in coding, but it is also important to have your own code style.

If the code you add to the file looks radically different from the existing code around it, the reader will lose rhythm while reading it. Avoid this situation.