HTML 语法和常用任务备忘单

在使用 HTML 时,方便地记住如何正确使用 HTML 标签以及如何应用它们会非常有帮助。MDN 为您提供了详尽的 HTML 参考文档,以及一套深入的教学 HTML 指南。然而,在很多情况下,我们只需要一些快速的提示。这正是备忘单的目的,为您提供一些常见用法的快速、准确、可直接使用的代码片段。

注意: HTML 标签必须根据其语义值使用,而不是外观。使用 CSS 总是可以彻底改变给定标签的外观和感觉,因此,在使用 HTML 时,请花时间关注其含义而非外观。

内联元素

“元素”是网页的单个组成部分。有些元素很大,像容器一样包含其他较小的元素。有些元素很小,被“嵌套”在较大的元素中。默认情况下,“内联元素”会彼此相邻显示在网页上。它们只占用页面上所需的宽度,像句子中的单词或并排放在一排书架上的书一样水平排列。所有内联元素都可以放置在 <body> 元素内。

内联元素:用法和示例
用法 Element 示例
链接 <a>
html
<a href="https://example.org">
A link to example.org</a>.
图像 <img>
html
<img src="beast.png" width="50" />
内联容器 <span>
html
Used to group elements: for example,
to <span style="color:blue">style
them</span>.
强调文本 <em>
html
<em>I'm posh</em>.
斜体文本 <i>
html
Mark a phrase in <i>italics</i>.
粗体文本 <b>
html
Bold <b>a word or phrase</b>.
重要文本 <strong>
html
<strong>I'm important!</strong>
高亮文本 <mark>
html
<mark>Notice me!</mark>
删除线文本 <s>
html
<s>I'm irrelevant.</s>
下标 <sub>
html
H<sub>2</sub>O
小文本 <small>
html
Used to represent the <small>small
print </small>of a document.
地址 <address>
html
<address>Main street 67</address>
文本引用 <cite>
html
For more monsters,
see <cite>The Monster Book of Monsters</cite>.
上标 <sup>
html
x<sup>2</sup>
内联引用 <q>
html
<q>Me?</q>, she said.
换行符 <br>
html
Line 1<br>Line 2
可能的换行符 <wbr>
html
<div style="width: 200px">
  Llanfair<wbr>pwllgwyngyll<wbr>gogerychwyrndrobwllllantysiliogogogoch.
</div>
Date <time>
html
Used to format the date. For example:
<time datetime="2020-05-24">
published on 23-05-2020</time>.
代码格式 <code>
html
This text is in normal format,
but <code>this text is in code
format</code>.
音频 <audio>
html
<audio controls>
  <source src="/shared-assets/audio/t-rex-roar.mp3" type="audio/mpeg">
</audio>
        
视频 <video>
html
<video controls width="250"
  src="/shared-assets/videos/flower.webm" >
  <a href="/shared-assets/videos/flower.webm">Download WebM video</a>
</video>

块级元素

另一方面,“块级元素”会占据网页的全部宽度。它们也会占据网页的整行;它们不会并排排列。相反,它们像论文中的段落或塔中的积木一样堆叠。

注意: 因为这个备忘单仅限于代表特定结构或具有特殊语义的少数元素,所以 <div> 元素故意未包含在内——因为 div 元素本身不代表任何内容,也没有任何特殊的语义。

用法 Element 示例
一个简单的段落 <p>
html
<p>I'm a paragraph</p>
<p>I'm another paragraph</p>
扩展引用 <blockquote>
html
They said:
<blockquote>The blockquote element indicates
an extended quotation.</blockquote>
附加信息 <details>
html
<details>
  <summary>HTML Cheat Sheet</summary>
  <p>Inline elements</p>
  <p>Block elements</p>
</details>
无序列表 <ul>
html
<ul>
  <li>I'm an item</li>
  <li>I'm another item</li>
</ul>
有序列表 <ol>
html
<ol>
  <li>I'm the first item</li>
  <li>I'm the second item</li>
</ol>
定义列表 <dl>
html
<dl>
  <dt>A Term</dt>
  <dd>Definition of a term</dd>
  <dt>Another Term</dt>
  <dd>Definition of another term</dd>
</dl>
水平分割线 <hr>
html
before<hr>after
文本标题 <h1>-<h6>
html
<h1> This is Heading 1 </h1>
<h2> This is Heading 2 </h2>
<h3> This is Heading 3 </h3>
<h4> This is Heading 4 </h4>
<h5> This is Heading 5 </h5>
<h6> This is Heading 6 </h6>