Tailwind CSS - 布局
Tailwind CSS:布局
Section titled “Tailwind CSS:布局”布局是任何网页设计的基石。Tailwind CSS 提供了一套强大而全面的工具类,用于控制布局的各个方面,从元素定位、堆叠顺序到创建复杂的响应式网格。
核心布局工具类参考
Section titled “核心布局工具类参考”下表提供了 Tailwind CSS 中最重要的布局相关工具类参考。它们是现代网页布局的基石。
| 主题 | 描述 |
|---|---|
纵横比 (aspect-ratio) | 将元素约束为固定的纵横比,非常适用于响应式图片和视频嵌入。 |
容器 (container) | 一个用于将容器宽度固定到当前断点(breakpoint),并自动水平居中的组件。 |
列 (columns) | 控制元素内的列数,创建杂志风格的文本布局。 |
断页/断列 (break-after/before/inside) | 控制页面或列在元素周围和内部如何中断的工具类。 |
盒模型 (box-sizing) | (box-border、box-content)工具类,用于控制浏览器如何计算元素的总大小。 |
显示 (display) | 控制元素的显示行为(例如,block、inline-block、flex、grid、hidden)。 |
浮动 (float, clear) | 用于定位元素的传统工具类。现代布局请使用 Flexbox 或 Grid。 |
隔离 (isolation) | 用于创建新的堆叠上下文(stacking context)的工具类,有助于管理 z-index。 |
对象适应 (object-fit) | 控制元素内容(如 <img> 或 <video>) 如何调整大小以适应其容器。 |
对象位置 (object-position) | 指定元素内容在其框内的对齐方式。 |
溢出 (overflow) | 控制如何处理溢出元素框的内容(overflow-hidden、overflow-auto)。 |
定位 (position) | 控制元素的定位策略(static、relative、absolute、fixed、sticky)。 |
上/右/下/左 (inset) | 指定 absolute、fixed 或 sticky 元素位置的工具类。 |
可见性 (visibility) | 控制元素的可见性(visible、invisible)。invisible 会隐藏元素但保留其在布局中的空间。 |
层叠顺序 (z-index) | 控制定位元素的堆叠顺序(stacking order)。值越高显示在越前方。 |
小项目:构建用户资料卡
Section titled “小项目:构建用户资料卡”本示例演示了如何结合多个布局工具类来构建一个常见的 UI 组件。请注意,卡片使用了 relative 定位来为 absolute 定位的状态徽章创建一个容器,然后使用 z-10 将其层叠到顶部。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Layout Mini-Project</title> <script src="https://cdn.tailwindcss.com"></script></head><body class="bg-slate-200 flex items-center justify-center min-h-screen">
<!-- 资料卡容器 --> <div class="max-w-sm mx-auto bg-white rounded-xl shadow-lg p-6 space-y-4">
<!-- 带有头像和状态的头部 --> <div class="flex items-center space-x-4"> <!-- 父元素为 'relative' 以包含 'absolute' 定位的徽章 --> <div class="relative"> <img class="w-20 h-20 rounded-full object-cover" src="https://i.pravatar.cc/150?u=a042581f4e29026704d" alt="User avatar"> <!-- 徽章为 'absolute' 定位,相对于图片容器 --> <div class="absolute bottom-0 right-0 h-5 w-5 bg-green-500 rounded-full border-2 border-white"></div> </div> <div> <h2 class="text-2xl font-bold text-slate-800">Elena Voyage</h2> <p class="text-slate-500">UI/UX Designer</p> </div> </div>
<!-- 个人简介部分 --> <div> <p class="text-slate-600">Creative designer with a passion for clean user interfaces and accessible design. Turning complex problems into beautiful, intuitive solutions.</p> </div>
<!-- Hidden 与 Invisible 演示 --> <div class="border-t pt-4"> <p class="text-sm text-slate-400">下面,'invisible' 占用空间,'hidden' 不占用。</p> <div class="flex space-x-2 mt-2"> <div class="w-1/3 h-10 bg-sky-300 rounded">Visible</div> <div class="w-1/3 h-10 bg-sky-300 rounded invisible">Invisible</div> <div class="w-1/3 h-10 bg-sky-300 rounded">Visible</div> <div class="w-1/3 h-10 bg-rose-300 rounded hidden">Hidden</div> </div> </div>
</div>
</body></html>