Skip to content

Tailwind CSS - 元素间距

space-* 工具类提供了一种强大的方式,可以在子元素之间添加一致的间距。你无需为每个子元素添加外边距,只需将一个 space-* 工具类应用于父容器即可。

在底层,Tailwind 使用“被切除了前脑的猫头鹰”选择器(* + *),为除第一个之外的所有子元素添加外边距。这确保了元素之间有间隙,而不会在第一个元素之前或最后一个元素之后添加不必要的空间。

这些工具类控制子元素沿水平或垂直轴的间距。

ClassDescription
space-x-{size}为子元素之间添加水平间距。例如,space-x-4 会为除第一个之外的所有子元素添加 1rem 的左外边距。
space-y-{size}为子元素之间添加垂直间距。例如,space-y-4 会为除第一个之外的所有子元素添加 1rem 的上外边距。
space-x-reverse反转水平间距的方向。与 flex-row-reverse 结合使用,以确保外边距被添加到正确的侧面。
space-y-reverse反转垂直间距的方向。与 flex-col-reverse 结合使用。

注意: {size} 对应于 Tailwind 的间距比例(例如,0、0.5、1、1.5、…、px)。

<div class="p-8 bg-slate-100 space-y-8">
<!-- 使用 space-x-4 的水平间距 -->
<div>
<h3 class="font-semibold mb-2">水平导航菜单 (`space-x-4`)</h3>
<div class="flex">
<div class="flex space-x-4 bg-white p-4 rounded-lg shadow">
<a href="#" class="px-3 py-2 text-slate-700 rounded-lg hover:bg-slate-100">Home</a>
<a href="#" class="px-3 py-2 text-slate-700 rounded-lg hover:bg-slate-100">About</a>
<a href="#" class="px-3 py-2 text-slate-700 rounded-lg hover:bg-slate-100">Projects</a>
<a href="#" class="px-3 py-2 text-slate-700 rounded-lg hover:bg-slate-100">Contact</a>
</div>
</div>
</div>
<!-- 使用 space-y-4 的垂直间距 -->
<div>
<h3 class="font-semibold mb-2">垂直列表 (`space-y-4`)</h3>
<div class="flex flex-col space-y-4 max-w-sm">
<div class="bg-white p-4 rounded-lg shadow">Item 1</div>
<div class="bg-white p-4 rounded-lg shadow">Item 2</div>
<div class="bg-white p-4 rounded-lg shadow">Item 3</div>
</div>
</div>
</div>

当你使用 flex-row-reverse 反转元素顺序时,space-x-* 工具类将错误地添加 margin-left。为解决此问题,你需要添加 space-x-reverse 类,它会告诉 Tailwind 转而应用 margin-right。

<!-- 此容器从右到左排列项目 -->
<div class="flex flex-row-reverse space-x-4 space-x-reverse bg-white p-4 rounded-lg shadow">
<div class="w-16 h-16 rounded-lg bg-rose-500 flex items-center justify-center text-white">1</div>
<div class="w-16 h-16 rounded-lg bg-rose-500 flex items-center justify-center text-white">2</div>
<div class="w-16 h-16 rounded-lg bg-rose-500 flex items-center justify-center text-white">3</div>
</div>

对于 Flexbox 和 Grid 布局,gap-* 工具类现在是添加元素之间间距的推荐方式。它们通常更简单、更可预测。

  • 在任何 flex 或 grid 容器中使用 gap-*。它是现代标准,不添加外部外边距,并能正确处理换行元素。
  • 当你没有使用 flex 或 grid,但仍想分隔一系列兄弟元素时,使用 space-*。它也适用于在元素之间添加分隔线,如下一节所示。

space-* 工具类与 divide-* 工具类完美配合,可在子元素之间添加边框。

<div class="flex flex-col space-y-4 divide-y divide-slate-200 max-w-sm">
<div class="pt-4">User Profile</div>
<div class="pt-4">Billing Information</div>
<div class="pt-4">Security Settings</div>
<div class="pt-4">Notifications</div>
</div>