Write HTML in a more sensible way

  • Disciplined code promotes teamwork,
  • The canonical code can be reducedbugTo deal with,
  • Regular code can reduce maintenance costs,
  • Normative code facilitates code review,
  • Getting into the habit of code specification helps programmers grow.

directory

1 introduction

2 Code Style

  • 2.1 Indent and line feed
  • 2.2 named
  • 2.3 the label
  • 2.4 attributes

Three general

  • 3.1 a DOCTYPE
  • 3.2 coding
  • 3.3 Introduction of CSS and JavaScript

4 head

  • 4.1 the title
  • 4.2 the favicon
  • 4.3 the viewport

5 pictures

6 the form

  • 6.1 Control Title
  • 6.2 the button
  • 6.3 Accessibility (A11Y)

7 the multimedia

8 HTML in the template

1 introduction

As a hypertext markup language to describe the structure of web pages, HTML has been widely used in Baidu. The goal of this document is to make the HTML code style consistent, easy to understand, and easy to maintain.

2 Code Style

2.1 Indent and line feed

use4A space as an indentation level is not allowed2A blank space ortabCharacters.

Explanation:

Indentation between non-HTML tags, such as the indentation of script or style tags, is the same as the indentation of script or style tags.

Example:

<style>
/* The first level of indentation of the style content is aligned with the style tag */
ul {
    padding: 0;
}
</style>
<ul>
    <li>first</li>
    <li>second</li>
</ul>
<script>
// The first level of indentation of the script code is aligned with the script tag to which it belongs
require(['app'].function (app) {
    app.init();
});
</script>
Copy the code

Each line shall not exceed120A character.

Explanation:

Excessively long code is difficult to read and maintain. However, considering the particularity of HTML, it is not mandatory.

2.2 named

classAll letters must be in lower case-Space.

classMust represent the content or functionality of the corresponding module or part and must not be named with style information.

Example:

<! -- good -->
<div class="sidebar"></div>
<! -- bad -->
<div class="left"></div>
Copy the code

The elementidThe page must be unique.

Explanation:

On the same page, different elements contain the same ID, which is inconsistent with the attribute meaning of ID. And using document.getelementByID can lead to hard-to-trace problems.

idAll letters in lower case are recommended-Space. The project must be consistent in style.

id,classNaming, as short as possible, avoids conflicts and is clear.

Example:

<! -- good -->
<div id="nav"></div>
<! -- bad -->
<div id="navigation"></div>
<! -- good -->
<p class="comment"></p>
<! -- bad -->
<p class="com"></p>
<! -- good -->
<span class="author"></span>
<! -- bad -->
<span class="red"></span>
Copy the code

Forbidden toHook script, create one without style informationclass.

Explanation:

Instead of allowing classes to be used only to let JavaScript select certain elements, classes should have unambiguous semantics and styles. Otherwise, CSS classes may overflow.

It is better to use id and attribute selection as hooks.

Same page, should avoid using the samenameid.

Explanation:

The IE browser will confuse the ID and name attributes of an element, and document.getelementById may get an unwanted element. So be careful when naming the element’s ID and name attributes.

A good practice is to use different nomenclature for ID and name.

Example:

<input name="foo">
<div id="foo"></div>
<script>
// IE6 will display INPUT
alert(document.getElementById('foo').tagName);
</script>
Copy the code

2.3 the label

The label name must be lowercase.

Example:

<! -- good -->
<p>Hello StyleGuide!</p>
<! -- bad -->
<P>Hello StyleGuide!</P>
Copy the code

Labels that do not need to be self-closed cannot be self-closed.

Explanation:

Common tags that do not need to be self-closed include INPUT, BR, IMG, and HR.

Example:

<! -- good -->
<input type="text" name="title">
<! -- bad -->
<input type="text" name="title" />
Copy the code

rightHTML5Indicates the closed labels that are allowed to be omitted.

Explanation:

Exceptions can be made for scenarios where code size is very critical. For example: the delivery system used by third party pages.

Example:

<! -- good -->
<ul>
    <li>first</li>
    <li>second</li>
</ul>
<! -- bad -->
<ul>
    <li>first
    <li>second
</ul>
Copy the code

Label usage must comply with label nesting rules.

Explanation:

For example, div must not be placed in p and tbody must be placed in table.

For detailed rules for tag nesting, see the Elements definition section in the HTML DTD.

The use of HTML tags should follow the semantics of the tags.

Explanation:

The following are common tag semantics

  • P – paragraph
  • H1, H2, H3, H4, H5, H6 – Level headings
  • Strong, em – emphasized
  • Insert ins –
  • Del – deletes
  • Abbr. – abbreviation for
  • Code – Code identifier
  • Cite – The title of a source work
  • Q – reference
  • Blockquote – a paragraph or long quote
  • Ul – Unordered list
  • Ol – Ordered list
  • Dl,dt, DD – Define lists

Example:

<! -- good -->
<p>Esprima serves as an important <strong>building block</strong> for some JavaScript language tools.</p>
<! -- bad -->
<div>Esprima serves as an important <span class="strong">building block</span> for some JavaScript language tools.</div>
Copy the code

Do not use tables for layout when CSS can fulfill the same requirements.

Explanation:

Semantic correctness should be maintained as far as compatibility allows. Exceptions are allowed for scenarios that have strict requirements for grid alignment and stretchability, such as complex multi-column forms.

The use of labels should be as simple as possible to reduce unnecessary labels.

Example:

<! -- good -->
<img class="avatar" src="image.png">
<! -- bad -->
<span class="avatar">
    <img src="image.png">
</span>
Copy the code

2.4 attributes

Attribute names must use lowercase letters.

Example:

<! -- good -->
<table cellspacing="0">.</table>
<! -- bad -->
<table cellSpacing="0">.</table>
Copy the code

Attribute values must be enclosed in double quotes.

Explanation:

Do not use single quotes. Do not use no quotes.

Example:

<! -- good -->
<script src="esl.js"></script>
<! -- bad -->
<script src='esl.js'></script>
<script src=esl.js></script>
Copy the code

Boolean attribute. It is recommended not to add an attribute value.

Example:

<input type="text" disabled>
<input type="checkbox" value="1" checked>
Copy the code

Custom attributes are recommendedxxx-Is a prefix, which is recommendeddata-.

Explanation:

Using prefixes helps distinguish custom attributes from standards-defined attributes.

Example:

<ol data-ui-type="Select"></ol>
Copy the code

Three general

3.1 a DOCTYPE

useHTML5doctypeTo enable standard mode, uppercase is recommendedDOCTYPE.

Example:

<! DOCTYPEhtml>
Copy the code

Enable IE Edge mode.

Example:

<meta http-equiv="X-UA-Compatible" content="IE=Edge">
Copy the code

inhtmlThe label is set correctlylangProperties.

Explanation:

Help improve the accessibility of the page, for example, let the speech synthesizer determine the pronunciation it should use, let the translation tool determine the translation language, etc.

Example:

<html lang="zh-CN">
Copy the code

3.2 coding

Pages must be in compact form with explicit character encodings. Of the specified character encodingmetaIt must beheadThe first immediate child of.

Explanation:

See the HTML5 Charset article.

Example:

<html>
    <head>
        <meta charset="UTF-8">.</head>
    <body>.</body>
</html>
Copy the code

HTMLFile Usage NoneBOMUTF-8Encoding.

Explanation:

Utf-8 encoding has wider adaptability. BOM can cause unnecessary interference when using programs or tools to process documents.

3.3 Introduction of CSS and JavaScript

The introduction ofCSSMust specifyrel="stylesheet".

Example:

<link rel="stylesheet" href="page.css">
Copy the code

The introduction ofCSSJavaScriptNeed not specifytypeProperties.

Explanation:

Text/CSS and text/javascript are the default values for type.

The presentation definition is placed externallyCSSIn, the behavior definition is placed externallyJavaScriptIn the.

Explanation:

Structure-style-behavior separation of code is beneficial for both readable and maintainable code.

inheadTo bring in everything the page needsCSSResources.

Explanation:

During page rendering, new CSS can cause elements to be recalculated and drawn, and pages to flicker.

JavaScriptIt should be placed at the end of the page or loaded asynchronously.

Explanation:

Placing the script in the middle of the page blocks the rendering of the page. For performance reasons, follow this advice if not necessary.

Example:

<body>
    <! -- a lot of elements -->
    <script src="init-behavior.js"></script>
</body>
Copy the code

Mobile environments or Web applications designed only for modern browsers, if referencing external sourcesURLThe protocol part is the same as the page. You are advised to omit the protocol prefix.

Explanation:

CSS is introduced using protocol-relative urls. In IE7/8, two requests are made. Whether to use protocol-relative urls should take into account the context for which the page is intended.

Example:

<script src="/ / s1.bdstatic.com/cache/static/jquery-1.10.2.min_f2fb5194.js"></script>
Copy the code

4 head

4.1 the title

The page must containtitleThe tag declares the title.

titleMust be asheadAnd immediately followingcharsetAfter the statement.

Explanation:

If the title contains characters other than ASCII, the browser must know the character encoding type to decode; otherwise, garbled characters may occur.

Example:

<head>
    <meta charset="UTF-8">
    <title>The page title</title>
</head>
Copy the code

4.2 the favicon

ensurefaviconCan be accessed.

Explanation:

When favicon is not specified, most browsers request favicon.ico in the Web Server root. To keep favicon accessible and avoid 404, you must follow one of two methods:

  1. In the Web Server root directoryfavicon.icoFile.
  2. uselinkSpecify the favicon.

Example:

<link rel="shortcut icon" href="path/to/favicon.ico">
Copy the code

4.3 the viewport

If the page is to be mobile-friendly, specify the pageviewport.

Explanation:

Viewport Meta Tag allows you to set the width and initial zoom of the viewport area to avoid improper page display on mobile devices.

For example, if your page width is less than 980px and you want to be iOS friendly, you should set the width of your viewPort to fit your page width. Also, because different mobile devices have different resolutions, device-width and device-height variables should be used when setting.

In addition, in order for viewPort to work properly, the layout of the page content style should be adjusted accordingly, such as avoiding absolute positioning. For more information about viewports, see the Safari Web Content Guide

5 pictures

banimgsrcThe value is empty. Lazy loading images should also be added by defaultsrc.

Explanation:

The SRC value is empty, it will cause the browser to reload the current page, reference: developer.yahoo.com/performance…

Avoid toimgAdd unnecessarytitleProperties.

Explanation:

Redundant titles affect the viewing experience and increase the page size.

Add for important imagesaltProperties.

Explanation:

Improves the user experience when images fail to load.

addwidthheightProperty to avoid page jitter.

There is a need to download the pictureimgLabel implementation, no download requirements of the image using CSS background.

Explanation:

  1. Product logo, user profile picture, user generated pictures and other pictures with potential download demand toimgForm realization, can facilitate the user to download.
  2. Images that do not need to be downloaded, such as ICONS, backgrounds and images used by code, should be realized by CSS background images as far as possible.

6 the form

6.1 Control Title

Controls with text titles must be usedlabelThe tag associates it with its title.

Explanation:

There are two ways:

  1. Place the controllabelInside.
  2. labelforProperty to the controlid.

The first is recommended to reduce unnecessary ids. If the DOM structure does not allow direct nesting, use the second.

Example:

<label><input type="checkbox" name="confirm" value="on">I have confirmed the above terms</label>
<label for="username">User name:</label> <input type="textbox" name="username" id="username">
Copy the code

6.2 the button

usebuttonElement must be specifiedtypeAttribute values.

Explanation:

The default type of the button element is Submit. If placed in the form element, clicking on it will result in a form submission. The type attribute must be given in order to display the distinction and facilitate understanding.

Example:

<button type="submit">submit</button>
<button type="button">cancel</button>
Copy the code

Try not to use button elementsnameProperties.

Explanation:

Due to browser compatibility issues, using the button’s name attribute can cause a number of hard-to-find problems. Please refer to this article for details.

6.3 Accessibility (A11Y)

Buttons that are responsible for major functions should be placed first in the DOM.

Explanation:

Buttons for major functions should be placed in the front of each other to improve accessibility. Specifying float: Right in CSS can result in the primary button being visually front and the primary button being backward in the DOM.

Example:

<! -- good -->
<style>
.buttons .button-group {
    float: right;
}
</style>
<div class="buttons">
    <div class="button-group">
        <button type="submit">submit</button>
        <button type="button">cancel</button>
    </div>
</div>
<! -- bad -->
<style>
.buttons button {
    float: right;
}
</style>
<div class="buttons">
    <button type="button">cancel</button>
    <button type="submit">submit</button>
</div>
Copy the code

When using JavaScript for form submission, you should make native submission work if possible.

Explanation:

Submission will not work if the browser JS runs incorrectly or if JS is turned off. Submission can continue if the action property of the form element and the Name property of the form control are specified correctly.

Example:

<form action="/login" method="post">
    <p><input name="username" type="text" placeholder="Username"></p>
    <p><input name="password" type="password" placeholder="Password"></p>
</form>
Copy the code

When developing a page for mobile devices, specify the input field based on the content typetypeProperties.

Explanation:

Specify input field types based on content types for a friendly input experience.

Example:

<input type="date">
Copy the code

7 the multimedia

When used in modern browsersaudioAs well asvideoWhen using the tag to play audio and video, pay attention to the format.

Explanation:

Audio should be covered as much as possible in the following formats:

  • MP3
  • WAV
  • Ogg

The video should be covered in the following format as far as possible:

  • MP4
  • WebM
  • Ogg

In support ofHTML5Is preferentially used in the browseraudiovideoTag to define audio and video elements.

Support for multiple browsers using retrogradation to plug-ins.

Example:

<audio controls>
    <source src="audio.mp3" type="audio/mpeg">
    <source src="audio.ogg" type="audio/ogg">
    <object width="100" height="50" data="audio.mp3">
        <embed width="100" height="50" src="audio.swf">
    </object>
</audio>
<video width="100" height="50" controls>
    <source src="video.mp4" type="video/mp4">
    <source src="video.ogg" type="video/ogg">
    <object width="100" height="50" data="video.mp4">
        <embed width="100" height="50" src="video.swf">
    </object>
</video>
Copy the code

Enable automatic playback of audio and video only when necessary.

inobjectInside the tag are instructions indicating that the browser does not support the tag.

Example:

<object width="100" height="50" data="something.swf">DO NOT SUPPORT THIS TAG</object>
Copy the code

8 HTML in the template

Indentation of template code takes precedence over indentation of HTML code.

Example:

<! -- good -->
{if $display == true}
<div>
    <ul>
    {foreach $item_list as $item}
        <li>{$item.name}<li>
    {/foreach}
    </ul>
</div>
{/if}
<! -- bad -->
{if $display == true}
    <div>
        <ul>
    {foreach $item_list as $item}
        <li>{$item.name}<li>
    {/foreach}
        </ul>
    </div>
{/if}
Copy the code

The basic principle of template code is to ensure correct syntax for individual HTML tags.

Example:

<! -- good -->
<li class="{if $item.type_id == $current_type}focus{/if}">{ $item.type_name }</li>
<! -- bad -->
<li {if $item.type_id= =$current_type} class="focus"{/if} >{ $item.type_name }</li>
Copy the code

If you need to output a fixed number of data in each row, you are advised to group the data first and then loop the output.

Example:

<! -- good -->
<table>
    {foreach $item_list as $item_group}
    <tr>
        {foreach $item_group as $item}
        <td>{ $item.name }</td>
        {/foreach}
    <tr>
    {/foreach}
</table>
<! -- bad -->
<table>
<tr>
    {foreach $item_list as $item}
    <td>{ $item.name }</td>
        {if $item@iteration is div by 5}
    </tr>
    <tr>
        {/if}
    {/foreach}
</tr>
</table>
Copy the code