Skip to content

Tailwind CSS - 间距

Tailwind CSS 间距(Spacing)终极指南

Section titled “Tailwind CSS 间距(Spacing)终极指南”

间距是任何良好布局的基础。Tailwind CSS 通过三个核心概念提供了一个强大且一致的间距管理系统:内边距(Padding)、外边距(Margin) 和 项目间距(Space Between)。掌握这些工具是构建简洁、专业的界面关键。

1. 内边距(Padding):元素内部空间

Section titled “1. 内边距(Padding):元素内部空间”

内边距工具类 (p-*) 在元素边框内部创建空间。这非常适合让内容在其容器边缘留出呼吸空间。

  • p-{size}: 应用内边距到所有四个方向。
  • px-{size}: 应用内边距到左侧和右侧(X轴)。
  • py-{size}: 应用内边距到顶部和底部(Y轴)。
  • pt-{size}、pr-{size}、pb-{size}、pl-{size}: 应用内边距到单个方向(上、右、下、左)。
<!-- 这个按钮有垂直内边距和更多水平内边距 -->
<button class="bg-blue-500 text-white font-bold py-2 px-4 rounded">
A Padded Button
</button>

2. 外边距(Margin):元素外部空间

Section titled “2. 外边距(Margin):元素外部空间”

外边距工具类 (m-*) 在元素边框外部创建空间,将其他元素推开。它们使用与内边距相同的语法(mx、my、mt 等)。一个独特的特性是可以使用负外边距来拉动元素或创建重叠效果。

<!-- 第二个头像使用负外边距与第一个头像重叠 -->
<div class="flex">
<img class="w-16 h-16 rounded-full border-2 border-white" src="..." alt="">
<img class="-ml-4 w-16 h-16 rounded-full border-2 border-white" src="..." alt="">
</div>

3. 项目间距(Space Between):现代的元素间隙处理方式

Section titled “3. 项目间距(Space Between):现代的元素间隙处理方式”

项目间距工具类(space-x-* 和 space-y-*)是一种现代且通常更优越的方式,用于在 flex、grid 或 flow-root 容器中的子元素之间添加间隙。与其为每个子元素添加外边距,不如为父元素添加一个 space-* 工具类。

为什么这更好? 它会自动处理在项目之间添加间距,而不会添加到第一个或最后一个项目,从而无需使用像 ... > :not(:last-child) 这样的复杂选择器。

<!-- 在所有子元素之间添加 1rem 的水平间隙 -->
<div class="flex space-x-4">
<div>01</div>
<div>02</div>
<div>03</div>
</div>

使用这个心智模型来决定使用哪个工具类:

目标使用的工具类理由
在盒子内部,内容和边框之间添加空间。内边距(Padding)用于内部呼吸空间。
将整个元素推离另一个元素。外边距(Margin)用于在外部创建空间。
在列表或项目组之间添加统一的间隙。项目间距(Space Between)这是最简洁、最易维护的项目分布方法。

此示例结合了所有三个概念来构建一个简单的卡片布局。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tailwind Spacing Example</title>
<link href="./dist/output.css" rel="stylesheet">
</head>
<body class="bg-slate-100">
<!-- 1. 外边距(MARGIN):`my-10` 和 `mx-auto` 工具类用于定位整个容器 -->
<div class="max-w-md mx-auto my-10 bg-white rounded-xl shadow-md overflow-hidden">
<!-- 2. 内边距(PADDING):`p-8` 工具类为卡片内部内容提供呼吸空间 -->
<div class="p-8">
<div class="uppercase tracking-wide text-sm text-indigo-500 font-semibold">Case study</div>
<a href="#" class="block mt-1 text-lg leading-tight font-medium text-black hover:underline">Finding customers for your new business</a>
<p class="mt-2 text-slate-500">Getting a new business off the ground is a lot of hard work.</p>
<!-- 3. 项目间距(SPACE BETWEEN):父元素上的 `space-x-4` 清晰地分隔了按钮 -->
<div class="mt-6 flex space-x-4">
<button class="px-4 py-2 bg-indigo-500 text-white rounded hover:bg-indigo-600">Read More</button>
<button class="px-4 py-2 bg-slate-200 text-slate-800 rounded hover:bg-slate-300">Share</button>
</div>
</div>
</div>
</body>
</html>

你的设计系统可能需要特定的间距值。你可以在 tailwind.config.js 文件中通过 theme.spacing 或 theme.extend.spacing 键轻松配置整个间距尺寸,或使用新值进行扩展。