Skip to content

Tailwind CSS - 自身对齐

Tailwind CSS 中的 align-self 工具类提供了对 Flexbox 或 Grid 容器内单个项目对齐方式的精细控制。它允许你覆盖容器的 align-items 属性,使特定元素沿容器的交叉轴独立定位。

虽然本教程中的示例使用 Tailwind Play CDN 进行快速演示,但实际项目应使用 npm 或 yarn 等包管理器以及 Tailwind CSS CLI 进行设置。这样可以充分发挥 Tailwind 的全部功能,包括自定义、插件和通过 PurgeCSS 进行性能优化。

# 1. 安装 Tailwind CSS
npm install -D tailwindcss
npx tailwindcss init
# 2. 在 tailwind.config.js 中配置你的模板路径
module.exports = {
content: ["./src/**/*.{html,js}"],
theme: {
extend: {},
},
plugins: [],
}
# 3. 将 Tailwind 指令添加到你的主 CSS 文件中
@tailwind base;
@tailwind components;
@tailwind utilities;
# 4. 启动构建过程
npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch

以下是控制单个弹性(flex)或网格(grid)项目交叉轴对齐的核心工具类。

类名CSS 属性
self-autoalign-self: auto;
self-startalign-self: flex-start;
self-endalign-self: flex-end;
self-centeralign-self: center;
self-stretchalign-self: stretch;
self-baselinealign-self: baseline;
  • self-auto:项目遵守其父容器的 align-items 值。这是默认行为。
  • self-start:将项目对齐到交叉轴的起始位置,忽略父容器的 align-items 值。
  • self-end:将项目对齐到交叉轴的结束位置。
  • self-center:将项目沿交叉轴居中。
  • self-stretch:拉伸项目以填充容器的高度(在基于行的 flex 容器中)或宽度(在基于列的 flex 容器中)。这要求项目在交叉轴上没有固定尺寸。
  • self-baseline:根据其文本内容的基线对齐项目。

让我们看看这些工具类的实际应用。下面的示例展示了一个灵活容器,其中大多数项目被拉伸,但有一个项目被专门对齐到中心,另一个对齐到末尾。请注意,我们还应用了响应式类(md:self-start)以在中等大小及以上屏幕上改变对齐方式。

<!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>
<title>Align Self Example</title>
</head>
<body class="bg-slate-100 p-8">
<h2 class="text-2xl font-bold text-slate-800 mb-4">User Profile Cards</h2>
<div class="flex h-72 items-stretch gap-4 p-4 bg-white rounded-lg shadow-lg">
<div class="flex-1 bg-sky-500 text-white p-4 rounded-md flex items-center justify-center">
<span>Default (Stretch)</span>
</div>
<div class="flex-1 bg-violet-500 text-white p-4 rounded-md flex items-center justify-center self-center md:self-start">
<span>I'm centered (or top-aligned on medium screens)</span>
</div>
<div class="flex-1 bg-sky-500 text-white p-4 rounded-md flex items-center justify-center">
<span>Default (Stretch)</span>
</div>
<div class="flex-1 bg-fuchsia-500 text-white p-4 rounded-md flex items-center justify-center self-end">
<span>I'm at the end</span>
</div>
</div>
</body>
</html>
  • self-stretch 不起作用? 检查项目是否有固定高度(如 h-24)或宽度。self-stretch 只有在项目在交叉轴上的尺寸不受约束时才能生效。
  • 弹性方向(Flex Direction)很重要:交叉轴取决于 flex-direction。在标准的 flex-row 中,交叉轴是垂直的。在 flex-col 中,交叉轴是水平的。对齐工具类将相应地工作。
  • 过度使用 align-self:如果你发现自己几乎对容器中的每个项目都应用了 align-self,请考虑重构你的 HTML 或使用多个 flex/grid 容器来达到所需的布局。通常,在父级使用 align-items 管理对齐方式会更清晰。

要完全掌握 align-self,请确保你对核心 CSS Flexbox 和 Grid 模型有扎实的理解。你可以在 MDN Web 文档中找到关于 Flexbox 和 Grid 的优秀资源。