文档结构
基本页面模板
每个 HTML5 文档以 <!DOCTYPE html> 开头,后跟带 lang 属性的 <html> 以支持可访问性和 SEO。<head> 包含元数据(charset、viewport、title),<body> 持有可见内容。viewport meta 标签确保在移动设备上正确渲染。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Web Page</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>Welcome to my page.</p>
</body>
</html>Head 部分与元数据
<head> 元素包含机器可读的元数据。charset 声明字符编码(UTF-8 覆盖几乎所有字符)。description meta 标签对 SEO 至关重要——搜索引擎在结果中显示它。在脚本上使用 defer 以在 HTML 解析后加载它们。
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page Title - Site Name</title>
<meta name="description" content="A brief description for SEO">
<meta name="author" content="John Doe">
<link rel="stylesheet" href="style.css">
<script src="app.js" defer></script>
</head>注释与条件注释
HTML 注释以 <!-- 开头,以 --> 结束。它们不在浏览器中显示,但在页面源代码中可见。注释适用于留下笔记、标记部分(TODO、FIXME)和文档。条件注释(仅 IE)已过时,但可能出现在遗留代码中。
<!-- This is a single-line comment -->
<!--
This is a
multi-line comment
-->
<!-- TODO: Add form validation -->
<!-- FIXME: Fix layout on mobile -->
<!--[if lt IE 9]>
<script src="html5shiv.js"></script>
<![endif]-->标题层次结构
HTML 提供六个标题级别,h1(最高)到 h6(最低)。按层次顺序使用,不跳过级别。搜索引擎使用标题理解页面结构。最佳实践:每页一个 h1,后跟 h2 用于主要部分,h3 用于子部分等。
<h1>Main Page Title</h1>
<h2>Major Section</h2>
<h3>Subsection</h3>
<h4>Sub-subsection</h4>
<h5>Minor Heading</h5>
<h6>Lowest Level Heading</h6>
<!-- Use only one h1 per page for SEO -->
<h1>Blog Post Title</h1>
<h2>Introduction</h2>
<h3>Background</h3>Div 与 Span 容器
<div> 是块级容器,用于分组元素和应用样式。<span> 是内联容器,用于样式化文本的小部分。两者都是无语义的通用元素——在适当情况下优先使用语义标签(header、nav、main、article)以获得更好的可访问性和 SEO。
<div class="container">
<div id="header" class="header">
<span class="logo">MySite</span>
<span class="tagline">Best Content</span>
</div>
<div class="content">
<p>Main <span class="highlight">content</span> here.</p>
</div>
</div>文本格式化
粗体、斜体与强调
<strong> 表示重要文本(屏幕阅读器会强调它),而 <b> 纯粹是视觉粗体。类似地,<em> 表示压力强调(语义),而 <i> 是视觉斜体。为可访问性优先使用 <strong> 和 <em>。<b> 和 <i> 可用于无语义重要性的样式目的。
<p>This is <strong>important</strong> text.</p>
<p>This is <b>bold</b> text.</p>
<p>This is <em>emphasized</em> text.</p>
<p>This is <i>italic</i> text.</p>
<p><strong>Warning:</strong> Do not touch!</p>Mark、Delete 与 Insert
<mark> 高亮相关文本(如搜索高亮)。<del> 标记删除的文本,<ins> 标记插入的文本——适用于显示编辑。<s> 划掉过时信息。<small> 用于旁注或版权。<u> 应谨慎使用,因为它类似于链接。
<p>Please <mark>highlight this</mark> word.</p>
<p>The price is <del>$99</del> <ins>$79</ins> now.</p>
<p><s>Old information</s> is struck through.</p>
<p>Use <u>underline</u> sparingly.</p>
<p>Small <small>print</small> for side comments.</p>上标与下标
<sub> 创建下标文本(基线以下),用于化学公式(H2O)和数学变量。<sup> 创建上标文本(基线以上),用于指数(x²)、序数(1st)和脚注。两者都是调整垂直位置和字体大小的内联元素。
<p>H<sub>2</sub>O is water.</p>
<p>E = mc<sup>2</sup> is Einstein's equation.</p>
<p>1st<sup>st</sup> January 2024</p>
<p>CO<sub>2</sub> emissions are rising.</p>
<p>x<sup>2</sup> + y<sup>2</sup> = r<sup>2</sup></p>引用与引文
<blockquote> 用于块级引用(缩进、多行)。<q> 用于内联短引用(自动添加引号)。cite 属性提供来源 URL。<cite> 标记作品标题或作者名。这些元素改善引用内容的语义标记。
<blockquote cite="https://example.com/source">
<p>The best way to predict the future is to invent it.</p>
<footer>— <cite>Alan Kay</cite></footer>
</blockquote>
<p>As <q cite="https://example.com">someone once said</q>,
knowledge is power.</p>代码与预格式化文本
<code> 标记内联代码片段(等宽字体)。<pre> 保留空白和换行用于预格式化文本。组合 <pre><code> 显示带有正确缩进的代码块。<kbd> 表示键盘输入。<samp> 用于程序输出,<var> 用于数学表达式中的变量。
<p>Use the <code>console.log()</code> function.</p>
<p>Press <kbd>Ctrl</kbd> + <kbd>C</kbd> to copy.</p>
<pre><code>function hello() {
console.log("Hello, World!");
return true;
}</code></pre>换行与水平线
<br> 在文本内创建换行(谨慎使用,优先用 CSS)。<hr> 创建水平线,表示部分之间的主题分隔。<wbr> 为长单词或 URL 建议换行机会,允许浏览器在最佳点断行。避免使用 <br> 进行间距——改用 CSS 边距。
<p>First line<br>Second line<br>Third line</p>
<p>Paragraph one.</p>
<hr>
<p>Paragraph two after a thematic break.</p>
<wbr><!-- word break opportunity for long URLs -->
https://example.com/<wbr>very<wbr>long<wbr>url链接与导航
基本链接
<a> 元素创建超链接。href 指定目标 URL。外部链接使用完整 URL(https://...),内部链接使用绝对路径(/about),相对链接使用文件路径(../index.html)。锚点链接(#section)跳转到同一页面上匹配 id 属性的元素。
<!-- External link -->
<a href="https://www.example.com">Visit Example</a>
<!-- Internal link (same site) -->
<a href="/about">About Us</a>
<!-- Relative link -->
<a href="../index.html">Home</a>
<!-- Anchor link (same page) -->
<a href="#section1">Jump to Section 1</a>链接目标与关系
target='_blank' 在新标签中打开链接——始终配对 rel='noopener noreferrer' 以确保安全(防止标签劫持攻击)。download 属性触发文件下载。mailto: 打开邮件客户端,tel: 在移动设备上发起电话呼叫。rel 属性定义关系(noopener、noreferrer、nofollow 用于 SEO)。
<!-- Open in new tab -->
<a href="https://example.com" target="_blank" rel="noopener noreferrer">
Open in new tab
</a>
<!-- Download link -->
<a href="report.pdf" download>Download PDF</a>
<!-- Email link -->
<a href="mailto:[email protected]?subject=Hello">Email us</a>
<!-- Phone link -->
<a href="tel:+1234567890">Call us</a>锚点目标
任何带 id 属性的元素都可以是锚点目标。带 href='#id' 的链接滚动到该元素。这对目录、脚注和单页导航至关重要。在 html 上添加 CSS 'scroll-behavior: smooth' 实现动画滚动。使用 'scroll-margin-top' 偏移固定标题。
<h2 id="introduction">Introduction</h2>
<p>Content here...</p>
<h2 id="features">Features</h2>
<p>Content here...</p>
<!-- Navigation menu linking to sections -->
<nav>
<a href="#introduction">Intro</a>
<a href="#features">Features</a>
</nav>
<!-- Smooth scroll via CSS: scroll-behavior: smooth -->图像与图形链接
将 <img> 包裹在 <a> 内使图像可点击。title 属性在悬停时创建工具提示(改善用户体验但 SEO 权重不高)。为可访问性,确保链接的图像有有意义的 alt 文本。对带标题的图像使用 figure/figcaption,这些图像也可能是链接。
<!-- Image as a link -->
<a href="https://example.com">
<img src="banner.jpg" alt="Click to visit">
</a>
<!-- Thumbnail linking to full image -->
<a href="full-size.jpg">
<img src="thumbnail.jpg" alt="View full image">
</a>
<!-- Link with title tooltip -->
<a href="https://example.com" title="Visit Example">
Hover for tooltip
</a>导航菜单
<nav> 为屏幕阅读器和 SEO 标识导航部分。使用 aria-current='page' 指示当前页面。面包屑帮助用户了解他们在站点层次结构中的位置。nav 内的列表提供语义结构。保持导航在各页面间一致以提高可用性。
<nav>
<ul>
<li><a href="/" aria-current="page">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
<!-- Breadcrumb navigation -->
<nav aria-label="Breadcrumb">
<ol>
<li><a href="/">Home</a></li>
<li><a href="/blog">Blog</a></li>
<li><a href="/blog/post" aria-current="page">Post</a></li>
</ol>
</nav>图像与多媒体
图像
始终为可访问性和 SEO 包含 alt 文本——它为屏幕阅读器描述图像,并在图像加载失败时显示。loading='lazy' 延迟屏幕外图像加载,提高页面速度。srcset 和 sizes 启用响应式图像——浏览器根据设备分辨率和视口选择最佳图像。始终指定 width 和 height 以防止布局偏移。
<!-- Basic image -->
<img src="photo.jpg" alt="A sunset over mountains" width="800" height="600">
<!-- Image with lazy loading -->
<img src="hero.jpg" alt="Hero banner" loading="lazy" decoding="async">
<!-- Responsive image with srcset -->
<img
src="medium.jpg"
srcset="small.jpg 480w, medium.jpg 800w, large.jpg 1200w"
sizes="(max-width: 600px) 480px, 800px"
alt="Responsive photo"
>Picture 元素
<picture> 提供艺术指导和格式回退。<source> 元素提供替代方案——浏览器选择第一个支持的格式(WebP/AVIF 更小)。media 属性为不同屏幕尺寸启用不同图像。最后的 <img> 是回退,必须始终存在。这对于提供完全不同的图像,它优于 srcset。
<picture>
<source srcset="webp-image.webp" type="image/webp">
<source srcset="avif-image.avif" type="image/avif">
<source srcset="wide.jpg" media="(min-width: 800px)">
<img src="fallback.jpg" alt="Art-directed image">
</picture>音频
<audio> 嵌入声音内容。controls 添加播放/暂停/音量控件。多个 <source> 元素提供格式回退(MP3 支持最广泛)。autoplay 受浏览器限制——静音自动播放通常被允许。loop 重复音频。如果音频不受支持,则显示内部文本。始终为用户体验提供控件。
<audio controls>
<source src="song.mp3" type="audio/mpeg">
<source src="song.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
<!-- Autoplay (muted required in most browsers) -->
<audio autoplay muted loop>
<source src="background.mp3" type="audio/mpeg">
</audio>视频
<video> 嵌入视频,带播放、暂停、音量和全屏控件。poster 在播放前设置缩略图。多个源提供格式回退(MP4/H.264 兼容性最好)。<track> 为可访问性添加字幕、说明或描述。playsinline 防止 iOS 上强制全屏。除非自动播放静音,否则始终包含控件。
<video controls width="640" height="360" poster="thumbnail.jpg">
<source src="movie.mp4" type="video/mp4">
<source src="movie.webm" type="video/webm">
<track kind="subtitles" src="subs.vtt" srclang="en" label="English">
Your browser does not support video.
</video>
<!-- Autoplay muted loop (common for backgrounds) -->
<video autoplay muted loop playsinline>
<source src="bg.mp4" type="video/mp4">
</video>Figure 与 Figcaption
<figure> 分组自包含内容,如图像、图表、代码列表或引用及其标题。<figcaption> 提供标题或图例。这种语义分组改善可访问性——屏幕阅读器宣布关系。图形可以从文本中引用('见图 1')并在布局中移动而不丢失上下文。
<figure>
<img src="chart.png" alt="Quarterly sales chart showing 20% growth">
<figcaption>Figure 1: Q4 2024 sales growth by region.</figcaption>
</figure>
<figure>
<blockquote>
<p>The best way to predict the future is to invent it.</p>
</blockquote>
<figcaption>— Alan Kay, 1971</figcaption>
</figure>Iframe 嵌入
<iframe> 嵌入外部内容(视频、地图、其他页面)。始终为可访问性包含 title 属性。loading='lazy' 改善屏幕外 iframe 的性能。allow 属性指定功能策略。sandbox 属性为安全限制 iframe 的功能。请谨慎——iframe 可能影响性能和安全。
<!-- Embed a YouTube video -->
<iframe
src="https://www.youtube.com/embed/dQw4w9WgXcQ"
width="560" height="315"
title="YouTube video"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media"
allowfullscreen>
</iframe>
<!-- Embed a map -->
<iframe
src="https://maps.google.com/maps?q=Paris&output=embed"
title="Map of Paris" loading="lazy">
</iframe>列表
无序列表
<ul> 创建无序(项目符号)列表。每项包裹在 <li> 中。list-style-type CSS 属性更改项目符号样式(disc、circle、square、none)。无序列表用于顺序无关的项。使用 list-style: none 和自定义样式用于导航菜单和功能列表。
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
<!-- Custom bullet style via CSS -->
<ul style="list-style-type: square;">
<li>First item</li>
<li>Second item</li>
</ul>有序列表
<ol> 创建有序(编号)列表用于顺序项。start 属性设置起始编号。reversed 以降序显示项。type 属性更改编号样式(1、A、a、I、i)。对步骤、排名或任何顺序重要的序列使用 <ol>。
<ol>
<li>First step</li>
<li>Second step</li>
<li>Third step</li>
</ol>
<!-- Start from a specific number -->
<ol start="5">
<li>Fifth item</li>
<li>Sixth item</li>
</ol>
<!-- Reverse order -->
<ol reversed>
<li>Countdown 3</li>
<li>Countdown 2</li>
<li>Countdown 1</li>
</ol>描述列表
<dl> 创建描述列表,将术语(<dt>)与描述(<dd>)配对。这适用于词汇表、常见问题页面和术语-定义对。多个 <dd> 可以描述一个 <dt>,反之亦然。描述列表提供定义表所缺乏的语义,改善可访问性。
<dl>
<dt>HTML</dt>
<dd>HyperText Markup Language</dd>
<dt>CSS</dt>
<dd>Cascading Style Sheets</dd>
<dt>JavaScript</dt>
<dd>A programming language for the web</dd>
</dl>嵌套列表
通过将 <ul> 或 <ol> 放在 <li> 内来嵌套列表。浏览器自动缩进嵌套列表并可能更改项目符号样式。嵌套创建层次结构,如目录、文件树或多级菜单。保持嵌套合理(2-3 级)以提高可用性。深度嵌套的列表变得难以阅读。
<ul>
<li>Fruits
<ul>
<li>Apple</li>
<li>Banana</li>
</ul>
</li>
<li>Vegetables
<ol>
<li>Carrot</li>
<li>Spinach</li>
</ol>
</li>
</ul>带链接的列表(导航)
<nav> 内的链接列表创建语义导航菜单。嵌套的 <ul> 元素形成下拉子菜单。此结构对屏幕阅读器可访问,且易于用 CSS 样式化。对交互式下拉菜单使用 aria 属性(aria-expanded、aria-haspopup)。基于列表的导航是可访问菜单的标准模式。
<nav>
<ul class="menu">
<li><a href="/">Home</a></li>
<li><a href="/products">Products</a>
<ul class="submenu">
<li><a href="/products/a">Product A</a></li>
<li><a href="/products/b">Product B</a></li>
</ul>
</li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>表格
基本表格
<table> 创建表格数据。<thead> 分组标题行,<tbody> 分组主体行,<tfoot> 分组页脚行。<tr> 是表格行,<th> 是标题单元格(粗体、居中),<td> 是数据单元格。使用 thead/tbody/tfoot 改善可访问性并启用更好的样式。表格应用于数据,而非布局。
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alice</td>
<td>30</td>
<td>New York</td>
</tr>
<tr>
<td>Bob</td>
<td>25</td>
<td>London</td>
</tr>
</tbody>
</table>跨单元格
colspan 使单元格跨多列(水平合并)。rowspan 使单元格跨多行(垂直合并)。这些属性创建复杂表格布局,如分组多列的标题。请谨慎使用跨单元格——它可能使表格难以被屏幕阅读器解析。始终测试可访问性。
<table border="1">
<tr>
<th colspan="2">Name</th>
<th rowspan="2">Age</th>
</tr>
<tr>
<th>First</th>
<th>Last</th>
</tr>
<tr>
<td>Alice</td>
<td>Smith</td>
<td>30</td>
</tr>
</table>表格标题与范围
<caption> 为表格提供标题,改善可访问性。<th> 上的 scope 属性告诉屏幕阅读器标题是应用于列(scope='col')还是行(scope='row')。这对复杂表格至关重要。对于更复杂的表格,使用 id 和 headers 属性显式关联单元格与其标题。
<table>
<caption>Employee Salary Report 2024</caption>
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Department</th>
<th scope="col">Salary</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Alice</th>
<td>Engineering</td>
<td>$95,000</td>
</tr>
</tbody>
</table>列组
<colgroup> 分组列以进行样式化。其中的 <col> 元素将样式(尤其是宽度)应用于特定列。这比为每个单元格设置宽度更高效。列组还支持 span 属性以一次样式化多列。使用此功能在所有行中保持一致的列宽。
<table>
<colgroup>
<col style="width: 30%;">
<col style="width: 50%;">
<col style="width: 20%;">
</colgroup>
<tr>
<th>Product</th>
<th>Description</th>
<th>Price</th>
</tr>
<tr>
<td>Laptop</td>
<td>15-inch laptop</td>
<td>$999</td>
</tr>
</table>样式化表格
border-collapse: collapse 将相邻边框合并为一个。使用 :nth-child(even) 实现斑马条纹行(改善可读性)。:hover 在鼠标悬停时高亮行。th 样式区分标题。保持表格样式干净易读——避免过多边框。响应式表格可能需要在包装器上使用 overflow-x: auto 以适应小屏幕。
<style>
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f4f4f4; }
tr:nth-child(even) { background-color: #f9f9f9; }
tr:hover { background-color: #e0e0e0; }
</style>
<table>
<tr><th>Name</th><th>Score</th></tr>
<tr><td>Alice</td><td>95</td></tr>
<tr><td>Bob</td><td>87</td></tr>
</table>表单与输入
表单 结构
<form> 包裹输入控件。action 指定提交 URL,method 是 GET(在 URL 中可见)或 POST(隐藏)。文件上传需要 enctype='multipart/form-data'。<fieldset> 分组相关字段,<legend> 提供标题。始终使用 for/id 匹配将 <label> 与输入关联以支持可访问性。
<form action="/submit" method="POST" enctype="multipart/form-data">
<fieldset>
<legend>Personal Information</legend>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</fieldset>
<button type="submit">Submit</button>
</form>输入类型
HTML5 引入了许多带内置验证和移动友好键盘的输入类型。type='email' 验证电子邮件格式。type='number' 提供微调按钮。type='date' 和 'time' 显示原生选择器。type='color' 打开颜色选择器。type='range' 创建滑块。带 accept 的 type='file' 限制文件类型。type='hidden' 存储不向用户显示的数据。
<input type="text" name="username" placeholder="Username">
<input type="email" name="email" required>
<input type="password" name="pwd" minlength="8">
<input type="number" name="age" min="0" max="120" step="1">
<input type="date" name="birthday">
<input type="time" name="appointment">
<input type="color" name="favcolor" value="#ff0000">
<input type="range" name="volume" min="0" max="100">
<input type="file" name="upload" accept="image/*">
<input type="hidden" name="token" value="abc123">Select 与 Textarea
<select> 创建下拉菜单。<optgroup> 用标签分组相关选项。<option> 定义选项;selected 属性预选一个。<textarea> 用于多行文本输入。rows 和 cols 设置可见大小。maxlength 限制字符数。placeholder 提供提示。两者都支持 required 和 disabled 属性。
<label for="country">Country:</label>
<select id="country" name="country">
<optgroup label="North America">
<option value="us">United States</option>
<option value="ca">Canada</option>
</optgroup>
<optgroup label="Europe">
<option value="uk">United Kingdom</option>
<option value="fr">France</option>
</optgroup>
</select>
<label for="bio">Bio:</label>
<textarea id="bio" name="bio" rows="4" cols="40"
maxlength="500" placeholder="Tell us about yourself"></textarea>复选框与单选按钮
复选框允许多选;单选按钮仅允许一个(当它们共享相同 name 时)。checked 属性预选一个选项。始终将输入包裹在 <label> 中以获得可点击文本。使用 <fieldset> 和 <legend> 分组相关选项以支持可访问性。仅当选中时值才发送到服务器。
<fieldset>
<legend>Select your interests:</legend>
<label><input type="checkbox" name="interest" value="tech" checked> Tech</label>
<label><input type="checkbox" name="interest" value="music"> Music</label>
<label><input type="checkbox" name="interest" value="sports"> Sports</label>
</fieldset>
<fieldset>
<legend>Choose a plan:</legend>
<label><input type="radio" name="plan" value="free" checked> Free</label>
<label><input type="radio" name="plan" value="pro"> Pro</label>
<label><input type="radio" name="plan" value="enterprise"> Enterprise</label>
</fieldset>表单验证
HTML5 提供内置客户端验证。required 防止空值提交。minlength/maxlength 约束文本长度。pattern 使用正则表达式进行自定义验证(title 属性指导用户)。type='email' 和 type='url' 验证格式。min/max 用于数字和日期。向表单添加 novalidate 以禁用验证。
<form>
<input type="text" name="username" required
minlength="3" maxlength="20"
pattern="[A-Za-z0-9_]+"
title="3-20 alphanumeric characters">
<input type="email" name="email" required>
<input type="url" name="website"
placeholder="https://example.com">
<input type="number" name="age" min="18" max="99">
<button type="submit">Submit</button>
</form>按钮与 Datalist
type='submit' 提交表单,type='reset' 清除所有字段,type='button' 是自定义按钮。<datalist> 为 <input> 元素提供自动补全建议——用 list/id 链接它们。与 <select> 不同,用户可以输入自定义值。这结合了文本输入的灵活性和建议的便利性。
<!-- Button types -->
<button type="submit">Submit Form</button>
<button type="reset">Reset</button>
<button type="button" onclick="alert('Hi')">Click Me</button>
<!-- Datalist for autocomplete suggestions -->
<label for="browser">Choose a browser:</label>
<input list="browsers" name="browser" id="browser">
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Safari">
<option value="Edge">
</datalist>语义化 HTML
Header 与导航
<header> 表示介绍性内容——通常是徽标、标题和导航。它可以出现在页面顶部或 <article> 或 <section> 内。<nav> 标识导航链接,帮助屏幕阅读器跳转到导航。一个页面可以有多个标题(例如,每个部分一个)。Header 与 head 不同——它是可见内容。
<header>
<h1>My Website</h1>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog">Blog</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
</header>