Tailwind CSS - 尺寸
Tailwind CSS - 尺寸
Section titled “Tailwind CSS - 尺寸”size-* 工具类是 Tailwind CSS v3.2 引入的一个便捷速记属性,用于同时设置元素的 width(宽度)和 height(高度)。它非常适用于创建统一尺寸的元素,如头像(avatars)、图标(icons)或颜色样本(color swatches)。
size-* 类接受与 w-*(宽度)和 h-*(高度)工具类相同的值,包括数字比例值、分数和关键词。
| 类名 | CSS 属性 | 常见用例 |
|---|---|---|
size-0 | width: 0px; height: 0px; | 完全收缩一个元素。 |
size-px | width: 1px; height: 1px; | 创建一个 1 像素的点或细边框。 |
size-4 | width: 1rem; height: 1rem; | 设置小型图标的尺寸(16x16px)。 |
size-16 | width: 4rem; height: 4rem; | 设置中型头像的尺寸(64x64px)。 |
size-1/2 | width: 50%; height: 50%; | 使元素变为其父元素大小的一半。 |
size-full | width: 100%; height: 100%; | 使元素填满其父容器。 |
size-auto | width: auto; height: auto; | 让浏览器根据内容确定尺寸。 |
size-min | width: min-content; height: min-content; | 将元素收缩到其最小固有尺寸。 |
size-max | width: max-content; height: max-content; | 将元素扩展到其最大固有尺寸。 |
size-fit | width: fit-content; height: fit-content; | 使元素尺寸适应其内容,但不超过可用空间。 |
实际应用:构建一个 UI 个人资料组件
Section titled “实际应用:构建一个 UI 个人资料组件”size 工具类在创建需要方形元素的组件时表现出色。在此示例中,我们将构建一个用户资料卡片,其中包含一个完美的方形头像和状态指示器。
示例:带头像的资料卡片
Section titled “示例:带头像的资料卡片”<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Tailwind Size Utility</title> <script src="https://cdn.tailwindcss.com"></script></head><body class="bg-gray-100 flex items-center justify-center min-h-screen">
<div class="bg-white p-6 rounded-lg shadow-lg flex items-center space-x-4"> <!-- Avatar Container --> <div class="relative flex-shrink-0"> <!-- Avatar Image --> <img class="size-16 rounded-full object-cover" src="https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=200" alt="用户头像"> <!-- Status Indicator --> <span class="absolute bottom-0 right-0 block size-4 bg-green-500 border-2 border-white rounded-full"></span> </div> <div> <p class="text-xl font-bold text-gray-900">Jane Doe</p> <p class="text-gray-600">Software Engineer</p> </div> </div>
</body></html>与所有 Tailwind 工具类一样,size 也可以响应式应用。这对于创建在不同设备上改变尺寸的元素非常有用。例如,一个 logo(标志)在移动设备上可能更小,而在桌面设备上可能更大。
<!-- 此 div 在移动设备上为 24x24,在中等屏幕上为 32x32,在大型屏幕上为 40x40 --><div class="size-24 md:size-32 lg:size-40 bg-blue-500 rounded-lg"></div>任意值与自定义
Section titled “任意值与自定义”对于非标准尺寸,你可以直接在 HTML 中使用任意值。对于你经常复用的尺寸,最好将它们添加到 tailwind.config.js 中。
<!-- 一个完美的 100x100 像素正方形 --><div class="size-[100px] bg-red-500"></div>module.exports = { theme: { extend: { // 这会添加一个 `size-card` 工具类 size: { 'card': '350px', } } }}何时使用 size 而非 w 和 h
Section titled “何时使用 size 而非 w 和 h”- 对方形元素使用
size:对于头像、图标、复选框以及其他统一尺寸的 UI 元素,它更简洁、更具表达力。 - 对矩形元素使用
w-*和h-*:当宽度和高度不同时,请坚持使用单独的工具类(例如,w-full h-64用于横幅)。