Bootstrap 5 容器

Bootstrap 5 容器

在上一章节中我们了解到 Bootstrap 需要一个容器元素来包裹网站的内容。

我们可以使用以下两个容器类:

  1. .container 类用于固定宽度并支持响应式布局的容器。
  2. .container-fluid 类用于 100% 宽度,占据全部视口(viewport)的容器。
.container
.container-fluid

固定宽度

.container 类用于创建固定宽度的响应式页面。

注意:宽度 (max-width) 会根据屏幕宽度同比例放大或缩小:

超级小屏幕
<576px
小屏幕
≥576px
中等屏幕
≥768px
大屏幕
≥992px
特大屏幕
≥1200px
超级大屏幕
≥1400px
max-width 100% 540px 720px 960px 1140px 1320px

以下实例中,我们可以尝试调整浏览器窗口的大小来查看容器宽度在不同屏幕中的变化:

实例

<div class="container">
  <h1>我的第一个 Bootstrap 页面</h1>
  <p>This is some text.</p>
</div>
亲自试一试 »

注意: 超级大屏幕 (≥1400px) 是 Bootstrap 5 新增加的, Bootstrap 4 最大的是特大屏幕 (≥1200px)。


100% 宽度

.container-fluid 类用于创建一个全屏幕尺寸的容器,容器始终跨越整个屏幕宽度 (width 始终为 100%):

实例

<div class="container-fluid">
  <h1>我的第一个 Bootstrap 页面</h1>
  <p>This is some text.</p>
</div>
亲自试一试 »


容器内边距

默认情况下,容器都有填充左右内边距,顶部和底部没有填充内边距。 Bootstrap 提供了一些间距类用于填充边距。 比如 .pt-5 就是用于填充顶部内边距:

实例

<div class="container pt-5"></div>
亲自试一试 »

容器的边框和颜色

Bootstrap 也提供了一些边框(border)和颜色(bg-dark、bg-primary等)类用于设置容器的样式:

实例

<div class="container p-5 my-5 border"></div>

<div class="container p-5 my-5 bg-dark text-white"></div>

<div class="container p-5 my-5 bg-primary text-white"></div>
亲自试一试 »

后面章节我们会详细说明这些样式。


响应式容器

你可以使用 .container-sm|md|lg|xl 类来创建响应式容器。

容器的 max-width 属性值会根据屏幕的大小来改变:

Class 超小屏幕
<576px
小屏幕
≥576px
中等屏幕
≥768px
大屏幕
≥992px
特大屏幕
≥1200px
超级大屏幕
≥1400px
.container-sm 100% 540px 720px 960px 1140px 1320px
.container-md 100% 100% 720px 960px 1140px 1320px
.container-lg 100% 100% 100% 960px 1140px 1320px
.container-xl 100% 100% 100% 100% 1140px 1320px
.container-xxl 100% 100% 100% 100% 100% 1320px

实例

<div class="container-sm">.container-sm</div>
<div class="container-md">.container-md</div>
<div class="container-lg">.container-lg</div>
<div class="container-xl">.container-xl</div>
<div class="container-xxl">.container-xxl</div>
亲自试一试 »