Skip to content

Tailwind CSS - 放置内容

place-content 工具类是 align-content 和 justify-content 的缩写,允许您在有多余空间时,控制整个网格或弹性布局项目组如何打包(排列)到其容器内。

关键区别: 使用 place-items 来对齐 项目在其自身单元格/空间内。使用 place-content 来对齐 整个项目组 在容器内。

这些类对于在多行弹性容器 (flex-wrap) 或网格布局中分配空间至关重要,尤其当网格轨道总大小小于网格容器时。

类CSS 属性描述
place-content-centerplace-content: center;将项目组居中排列在容器中。
place-content-startplace-content: start;将项目组排列在容器的起始位置。
place-content-endplace-content: end;将项目组排列在容器的结束位置。
place-content-betweenplace-content: space-between;均匀分布项目;第一个项目在起始位置,最后一个项目在结束位置。
place-content-aroundplace-content: space-around;在每个项目周围分配相等的空间。
place-content-evenlyplace-content: space-evenly;在项目之间和两端分配相等的空间。
place-content-stretchplace-content: stretch;拉伸项目以填充容器(适用于网格布局)。

此示例展示了 place-content 如何对齐一个自动换行的标签列表。请注意,对齐方式会根据应用于弹性容器的类而改变。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/dist/output.css" rel="stylesheet">
<title>Tag List with place-content</title>
</head>
<body class="bg-slate-50 p-8">
<div class="max-w-xl mx-auto">
<!-- 示例 1: place-content-start -->
<h2 class="text-xl font-semibold text-slate-700 mb-2">`place-content-start`</h2>
<div class="flex flex-wrap gap-2 p-4 bg-sky-100 rounded-lg h-32 place-content-start mb-8">
<span class="px-3 py-1 bg-sky-500 text-white rounded-full text-sm">React</span>
<span class="px-3 py-1 bg-sky-500 text-white rounded-full text-sm">Vue</span>
<span class="px-3 py-1 bg-sky-500 text-white rounded-full text-sm">Svelte</span>
</div>
<!-- 示例 2: place-content-center -->
<h2 class="text-xl font-semibold text-slate-700 mb-2">`place-content-center`</h2>
<div class="flex flex-wrap gap-2 p-4 bg-amber-100 rounded-lg h-32 place-content-center mb-8">
<span class="px-3 py-1 bg-amber-500 text-white rounded-full text-sm">JavaScript</span>
<span class="px-3 py-1 bg-amber-500 text-white rounded-full text-sm">TypeScript</span>
</div>
<!-- 示例 3: place-content-between -->
<h2 class="text-xl font-semibold text-slate-700 mb-2">`place-content-between`</h2>
<div class="grid grid-cols-2 gap-4 p-4 bg-emerald-100 rounded-lg h-48 place-content-between">
<div class="p-4 bg-emerald-500 rounded-lg text-white">Item 1</div>
<div class="p-4 bg-emerald-500 rounded-lg text-white">Item 2</div>
<div class="p-4 bg-emerald-500 rounded-lg text-white">Item 3</div>
<div class="p-4 bg-emerald-500 rounded-lg text-white">Item 4</div>
</div>
<!-- 常见错误 -->
<div class="mt-12 bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded-md">
<p class="font-bold">调试技巧</p>
<p>如果 `place-content` 在弹性容器上不起作用,请确保已启用 `flex-wrap`,并且容器具有明确定义的高度 (`h-*`) 或 `min-height`,使其大于其内容。此工具类仅在存在额外空间可供分配时才适用!</p>
</div>
</div>
</body>
</html>