您现在的位置是:网站首页 > HTML编码规范文章详情
HTML编码规范
陈川 【 HTML 】 16012人已围观
1. 文档类型声明
Bad
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
Good
<!DOCTYPE html>
使用最新的HTML5文档类型声明。
2. 字符集定义
Bad
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
Good
<meta charset="UTF-8">
使用UTF-8字符集,这是HTML5推荐的编码方式。
3. 使用语义化标签
Bad
<div id="header">…</div>
<div id="content">…</div>
<div id="footer">…</div>
Good
<header>…</header>
<main>…</main>
<footer>…</footer>
使用语义化的HTML5标签,如<header>
, <main>
, <footer>
等。
4. 关闭空元素
Bad
<img src="image.jpg" alt="Image" />
Good
<img src="image.jpg" alt="Image">
HTML5中,空元素不需要斜杠结尾。
5. 属性值必须使用引号
Bad
<input type=text name=field value=initial>
Good
<input type="text" name="field" value="initial">
属性值应始终用引号包围。
6. 避免内联样式
Bad
<p style="font-size: 16px; color: #333;">Text</p>
Good
<style>
p {
font-size: 16px;
color: #333;
}
</style>
<p>Text</p>
将样式分离到CSS文件或内部样式表中。
7. 图片的alt属性
Bad
<img src="image.jpg">
Good
<img src="image.jpg" alt="A description of the image">
提供有意义的alt文本,以便于辅助技术使用。
8. 表单元素的label
Bad
<label>Username</label>
<input type="text" name="username">
Good
<label for="username">Username</label>
<input type="text" id="username" name="username">
使用for
属性关联<label>
和<input>
。
9. 使用有序和无序列表
Bad
<div>Item 1</div>
<div>Item 2</div>
Good
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
使用<ul>
或<ol>
代替多个<div>
元素。
10. 链接的target属性
Bad
<a href="url" target="_blank">Link</a>
Good
<a href="url">Link</a>
除非有特殊理由,否则不推荐自动打开新窗口。
11. 保持HTML结构清晰
Bad
<body>
<h1>Heading</h1>
<p>Paragraph</p>
<script>…</script>
<link rel="stylesheet" href="style.css">
</body>
Good
<head>
<title>Title</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Heading</h1>
<p>Paragraph</p>
<script>…</script>
</body>
将元信息放在<head>
中,内容放在<body>
中。
12. 无障碍性
Bad
<button>Click me</button>
Good
<button aria-label="Click this button to submit the form">Click me</button>
使用ARIA属性提高无障碍性。
13. 表单验证
Bad
<input type="email">
Good
<input type="email" required>
使用required
和其他HTML5验证属性。
14. 避免使用框架
Bad
<frameset>
<frame src="frame1.html">
<frame src="frame2.html">
</frameset>
Good
<!-- Use responsive design instead -->
现代Web设计倾向于响应式布局而非框架。
15. 使用注释
Bad
<!-- This is a comment -->
Good
<!-- This is a comment explaining what follows or precedes -->
提供有用的注释,而不是简单的声明。
以上示例仅涵盖了部分HTML编码规范,但遵循这些基本规则将显著提升代码质量和网站的用户体验。在实际开发中,还应参考W3C标准和相关最佳实践,以保持代码的现代性和兼容性。
站点信息
- 建站时间:2017-10-06
- 网站程序:Koa+Vue
- 本站运行:
- 文章数量:
- 总访问量:
- 微信公众号:扫描二维码,关注我