Skip to content

Tailwind CSS - 自身对齐

精通 justify-self 实现网格项目对齐

Section titled “精通 justify-self 实现网格项目对齐”

在 CSS 网格布局(CSS Grid layouts)中,justify-self 是一个强大的 CSS 属性,用于在其指定的网格区域内,沿着主轴(或内联轴)对单个网格项目(grid item)进行对齐。它允许你为特定的项目覆盖网格容器(grid container)的默认对齐方式(justify-items),从而精确控制布局。本教程将探讨如何有效地使用 Tailwind CSS 的 justify-self 工具类。

Tailwind CSS 提供了一整套工具类,这些工具类直接映射到 justify-self CSS 属性。

类名CSS 属性
justify-self-startjustify-self: start;
justify-self-endjustify-self: end;
justify-self-centerjustify-self: center;
justify-self-stretchjustify-self: stretch;
justify-self-autojustify-self: auto;

关键概念:justify-self 与 justify-items

Section titled “关键概念:justify-self 与 justify-items”

对于刚接触 CSS Grid 的开发者来说,这通常是一个容易混淆的地方。理解它们之间的区别至关重要:

  • justify-items:设置在网格容器上的属性。它定义了该网格内所有项目的默认 justify-self 对齐方式。
  • justify-self:设置在单个网格项目上的属性。它只覆盖特定项目的 justify-items 值。

观察不同项目在同一个网格容器中如何表现是理解 justify-self 作用的最佳方式。在此示例中,父级网格具有 justify-items-start,这意味着所有项目默认将对齐到起始位置。然后,我们将使用 justify-self-* 工具类来覆盖特定项目上的此设置。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tailwind CSS Justify Self Demo</title>
<!-- Assuming a build process links your compiled CSS -->
<link href="/dist/output.css" rel="stylesheet">
</head>
<body class="bg-slate-100 p-8">
<div class="max-w-3xl mx-auto">
<h2 class="text-2xl font-bold text-slate-800 mb-4">Dashboard Widgets</h2>
<!--
网格容器
- `grid-cols-2`:创建一个两列网格。
- `gap-4`:在网格项目之间添加间距。
- `justify-items-start`:将所有项目的默认水平对齐设置为起始位置。
- 在中等屏幕 (`md`) 上,我们将默认值更改为拉伸以呈现不同的外观。
-->
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 justify-items-start md:justify-items-stretch bg-slate-300 p-4 rounded-lg">
<!-- 项目 1:继承父级的 `justify-items-start` -->
<div class="bg-blue-500 text-white p-4 rounded">
<h3 class="font-bold">User Profile</h3>
<p class="text-sm">Default (Starts)</p>
</div>
<!-- 项目 2:被 `justify-self-end` 覆盖 -->
<div class="bg-red-500 text-white p-4 rounded justify-self-end">
<h3 class="font-bold">Logout Button</h3>
<p class="text-sm">justify-self-end</p>
</div>
<!-- 项目 3:被 `justify-self-center` 覆盖 -->
<div class="bg-green-500 text-white p-4 rounded justify-self-center">
<h3 class="font-bold">Status</h3>
<p class="text-sm">justify-self-center</p>
</div>
<!--
项目 4:被 `justify-self-stretch` 覆盖
这将填充其网格单元格的水平空间。
-->
<div class="bg-purple-500 text-white p-4 rounded justify-self-stretch">
<h3 class="font-bold">Notifications</h3>
<p class="text-sm">justify-self-stretch</p>
</div>
</div>
</div>
</body>
</html>

与所有 Tailwind 工具类一样,justify-self 可以在不同的断点(breakpoint)处有条件地应用。这对于创建健壮的响应式布局至关重要。在我们的示例中,父级的 justify-items 在中等屏幕 (md:justify-items-stretch) 上会发生变化,你也可以类似地将响应式前缀应用于单个项目:

<!-- 此项目在小屏幕上居中,在中等屏幕及以上对齐到起始位置 -->
<div class="justify-self-center md:justify-self-start ...">...</div>
  • 表单布局:将“提交”按钮对齐到其网格单元格的末尾,而其他输入字段则拉伸。
  • 卡片网格:使网格中的大多数卡片拉伸以填充空间,但有一个特色卡片具有不同的对齐方式。
  • 页面头部:在单个网格容器中,将标志对齐到起始位置,导航对齐到中心,用户菜单对齐到末尾。