A guide to writing HTML code

高洛峰
Release: 2017-02-24 10:12:31
Original
1082 people have browsed it

General convention

Tag

Self-closing tag, no need to close (for example: img input br hr, etc.);
Optional closing tag, which needs to be closed (for example: or );
Reduce the number of tags as much as possible;

<img src="images/google.png" alt="Google">
<input type="text" name="title">

<ul>
  <li>Style</li>
  <li>Guide</li>
</ul>

<!-- Not recommended -->
<span class="avatar">
  <img src="...">
</span>

<!-- Recommended -->
<img class="avatar" src="...">
Copy after login

Class and ID

class should be named after the function or content, not the expression;
class and id should be named in lowercase letters, multiple When forming words, use dash-separation;
Use unique ids as Javascript hooks and avoid creating classes without style information;

<!-- Not recommended -->
<p class="j-hook left contentWrapper"></p>

<!-- Recommended -->
<p id="j-hook" class="sidebar content-wrapper"></p>
Copy after login

Attribute Order

HTML attributes should appear in a specific order to ensure readability.

id
class
name
data-xxx
src, for, type, href
title, alt
aria-xxx, role

<a id="..." class="..." data-modal="toggle" href="###"></a>

<input class="form-control" type="text">

<img src="..." alt="...">
Copy after login

Quotation marks

Use double quotation marks uniformly for the definition of attributes.

<!-- Not recommended -->
<span id=&#39;j-hook&#39; class=text>Google</span>

<!-- Recommended -->
<span id="j-hook" class="text">Google</span>
Copy after login

bnesting

a Nesting of p is not allowed. This constraint is a semantic nesting constraint, and there are other constraints that are different from it Strict nesting constraints, such as a is not allowed to nest a.

Strict nesting constraints are not allowed in all browsers; as for semantic nesting constraints, most browsers will handle fault tolerance, and the generated document trees may be different from each other.

Semantic nesting constraints

  • used under