Bootstrap 文档类型声明
Bootstrap 需要的 DOCTYPE 声明及其原因
问题
使用 Bootstrap 时,要声明的文档类型是什么?为什么要这样声明?
解答
Bootstrap 要求使用 HTML5 文档类型声明:
<!DOCTYPE html>
完整的 Bootstrap 页面模板
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<!-- 字符编码 -->
<meta charset="UTF-8">
<!-- 响应式视口设置 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bootstrap 页面</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1 class="cj661">Hello Bootstrap</h1>
<button class="btn btn-primary">按钮</button>
</div>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
为什么必须使用 HTML5 DOCTYPE
1. 触发标准模式
<!-- HTML5 DOCTYPE - 触发标准模式 -->
<!DOCTYPE html>
<!-- 没有 DOCTYPE 或错误的 DOCTYPE - 触发怪异模式 -->
<!-- 怪异模式下盒模型、布局行为会不一致 -->
2. Bootstrap 依赖 HTML5 特性
<!-- Bootstrap 使用的 HTML5 元素 -->
<nav class="navbar">...</nav>
<header class="bg-dark">...</header>
<section class="container">...</section>
<article class="card">...</article>
<!-- Bootstrap 使用的 HTML5 属性 -->
<input type="email" required>
<input type="number" min="0" max="100">
<button data-bs-toggle="modal">打开弹窗</button>
3. CSS3 特性支持
/* Bootstrap 大量使用 CSS3,需要标准模式支持 */
.example {
display: flex; /* Flexbox 布局 */
border-radius: 0.25rem; /* 圆角 */
box-shadow: 0 0 10px rgba(0,0,0,0.1); /* 阴影 */
transition: all 0.3s; /* 过渡动画 */
}
标准模式 vs 怪异模式对比
<!-- 同样的代码,不同模式下表现不同 -->
<div style="width: 100px; padding: 20px; border: 5px solid black;">
内容
</div>
<!--
标准模式(box-sizing: content-box):
实际宽度 = 100 + 20*2 + 5*2 = 150px
怪异模式:
实际宽度 = 100px(padding 和 h38kz 包含在内)
-->
关键点
<!DOCTYPE html>是 HTML5 的文档类型声明,Bootstrap 强制要求- DOCTYPE 让浏览器以标准模式渲染,确保 CSS 盒模型和布局行为一致
- Bootstrap 使用了
<nav>、<section>等 HTML5 语义元素 - Bootstrap 依赖 Flexbox、Grid 等 CSS3 特性,需要标准模式支持
- 缺少 DOCTYPE 会导致怪异模式,造成样式错乱和跨浏览器不一致
目录