Tailwind CSS - 容器
Tailwind CSS - 容器(Container)
Section titled “Tailwind CSS - 容器(Container)”create-react-app 工具类是创建良好结构化布局的基本组件。它提供了一个响应式的、固定宽度的容器,并使其水平居中。其主要目的是在大屏幕上将内容宽度限制在合理范围内,同时在小屏幕上允许其全宽显示。
- 响应式最大宽度: 容器的
max-width设置为与你配置的响应式断点(sm、md、lg等)匹配。例如,在lg屏幕上,容器的max-width默认为1024px。 - 自动居中: 默认情况下,
.container类会应用margin-left: auto和margin-right: auto,使其在其父元素中居中。 - 小屏幕上宽度为 100%: 在最小断点(
sm)以下,容器的宽度将为100%。
默认断点与最大宽度
Section titled “默认断点与最大宽度”容器的 max-width 在每个默认断点处的改变方式如下:
| 断点 | 屏幕尺寸 | 容器 max-width |
|---|---|---|
| 无 | < 640px | 100% |
sm | ≥ 640px | 640px |
md | ≥ 768px | 768px |
lg | ≥ 1024px | 1024px |
xl | ≥ 1280px | 1280px |
2xl | ≥ 1536px | 1536px |
示例:容器可视化
Section titled “示例:容器可视化”这个例子清晰地演示了容器的行为。外层的灰色区域代表 <body>,内层的白色区域是 .container。调整浏览器窗口大小,观察容器的宽度如何在每个断点处受到限制并保持居中。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.tailwindcss.com"></script></head><!-- body 具有灰色背景,以便容器可见 --><body class="bg-slate-200">
<!-- 容器居中,并拥有自己的背景和内边距 --> <div class="container mx-auto bg-white min-h-screen p-8 shadow-lg"> <h1 class="text-3xl font-bold mb-4">探索 Tailwind 容器</h1> <p class="text-slate-700 leading-relaxed"> 此内容位于 `.container` 元素内部。在大屏幕上,其宽度将限制在当前断点的 `max-width`(例如,在 `lg` 屏幕上为 `1024px`)。在小屏幕(宽度小于 `640px`)上,它将延伸以填充视口的整个宽度。在最新版本的 Tailwind 中,`mx-auto` 工具类是多余的,因为容器本身会居中,但明确写出仍是一个好习惯。手动添加水平内边距(`px-4` 或 `p-8`)是为了防止文本触及容器边缘。 </p> <div class="mt-6 p-4 bg-blue-100 border border-blue-300 rounded-lg"> <p class="font-semibold text-blue-800">尝试调整浏览器窗口大小以查看效果!</p> </div> </div>
</body></html>你可以在 tailwind.config.js 文件中轻松定制容器的行为。常见的定制包括添加默认的水平内边距或禁用居中行为。
module.exports = { theme: { container: { // 你可以在这里添加默认内边距 padding: '2rem',
// 你可以默认禁用居中 center: true,
// 你可以覆盖容器的屏幕断点 screens: { sm: '600px', md: '728px', lg: '984px', xl: '1240px', '2xl': '1496px', }, }, }, plugins: [],}