1. 核心概念
  2. 响应式设计

核心概念

响应式设计

使用响应式工具变体构建自适应用户界面。

概述(Overview)

Tailwind 中的每个工具类都可以在不同的断点处有条件地应用,这使得在不离开 HTML 的情况下构建复杂的响应式界面变得轻而易举。

🌐 Every utility class in Tailwind can be applied conditionally at different breakpoints, which makes it a piece of cake to build complex responsive interfaces without ever leaving your HTML.

首先,确保你已经在文档的 <head> 中添加了 viewport 元标签

🌐 First, make sure you've added the viewport meta tag to the <head> of your document:

index.html
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

然后,如果要添加一个实用工具但只希望它在特定断点生效,你只需在实用工具前加上断点名称,然后跟上 : 字符:

🌐 Then to add a utility but only have it take effect at a certain breakpoint, all you need to do is prefix the utility with the breakpoint name, followed by the : character:

HTML
<!-- Width of 16 by default, 32 on medium screens, and 48 on large screens --><img class="w-16 md:w-32 lg:w-48" src="..." />

受常见设备分辨率的启发,默认有五个断点:

🌐 There are five breakpoints by default, inspired by common device resolutions:

断点前缀最小宽度CSS
sm40rem (640px)@media (width >= 40rem) { ... }
md48rem (768px)@media (width >= 48rem) { ... }
LG64rem (1024px)@media (width >= 64rem) { ... }
XL80rem (1280px)@media (width >= 80rem) { ... }
2XL96 rem (1536px)@media (width >= 96rem) { ... }

这适用于框架中的每一个实用类,这意味着你可以在指定的断点几乎改变任何东西——甚至像字母间距或光标样式这样的东西也可以更改。

🌐 This works for every utility class in the framework, which means you can change literally anything at a given breakpoint — even things like letter spacing or cursor styles.

这是一个营销页面组件的简单示例,它在小屏幕上使用堆叠布局,在大屏幕上使用并排布局:

🌐 Here's a simple example of a marketing page component that uses a stacked layout on small screens, and a side-by-side layout on larger screens:

<div class="mx-auto max-w-md overflow-hidden rounded-xl bg-white shadow-md md:max-w-2xl">  <div class="md:flex">    <div class="md:shrink-0">      <img        class="h-48 w-full object-cover md:h-full md:w-48"        src="/img/building.jpg"        alt="Modern building architecture"      />    </div>    <div class="p-8">      <div class="text-sm font-semibold tracking-wide text-indigo-500 uppercase">Company retreats</div>      <a href="#" class="mt-1 block text-lg leading-tight font-medium text-black hover:underline">        Incredible accommodation for your team      </a>      <p class="mt-2 text-gray-500">        Looking to take your team away on a retreat to enjoy awesome food and take in some sunshine? We have a list of        places to do just that.      </p>    </div>  </div></div>

以下是上面示例的工作原理:

🌐 Here's how the example above works:

  • 默认情况下,外部 divdisplay: block,但通过添加 md:flex 工具,它在中等及更大屏幕上会变为 display: flex
  • 当父元素是一个弹性容器时,我们希望确保图片永远不会缩小,因此我们添加了 md:shrink-0 来防止在中等屏幕及更大屏幕上缩小。从技术上讲,我们本可以只使用 shrink-0,因为它在小屏幕上不会有任何效果,但由于它只在 md 屏幕上才重要,因此在类名中明确这一点是一个好主意。
  • 在小屏幕上,图片默认会自动占满整个宽度。在中等屏幕及以上,我们将宽度限制为固定大小,并使用 md:h-full md:w-48 确保图片占满整个高度。

在这个例子中我们只使用了一个断点,但你也可以轻松地使用 smlgxl2xl 响应前缀在其他尺寸下自定义这个组件。

🌐 We've only used one breakpoint in this example, but you could easily customize this component at other sizes using the sm, lg, xl, or 2xl responsive prefixes as well.

移动端优先(Working mobile-first)

Tailwind 使用移动优先断点系统,类似于你在 Bootstrap 等其他框架中可能习惯的系统。

🌐 Tailwind uses a mobile-first breakpoint system, similar to what you might be used to in other frameworks like Bootstrap.

这意味着未加前缀的工具类(如 uppercase)在所有屏幕尺寸上都有效,而加前缀的工具类(如 md:uppercase)仅在指定的断点及以上尺寸生效。

🌐 What this means is that unprefixed utilities (like uppercase) take effect on all screen sizes, while prefixed utilities (like md:uppercase) only take effect at the specified breakpoint and above.

针对移动端屏幕(Targeting mobile screens)

这种方法最让人惊讶的地方在于,要为移动端设置样式,你需要使用没有前缀的工具版本,而不是带有 sm: 前缀的版本。不要把 sm: 理解为“在小屏幕上”,而应理解为“在小的断点上”。

🌐 Where this approach surprises people most often is that to style something for mobile, you need to use the unprefixed version of a utility, not the sm: prefixed version. Don't think of sm: as meaning "on small screens", think of it as "at the small breakpoint".

不要使用 sm: 来针对移动设备

HTML
<!-- This will only center text on screens 640px and wider, not on small screens --><div class="sm:text-center"></div>

使用无前缀的工具类来针对移动端,并在更大的断点上覆盖它们

HTML
<!-- This will center text on mobile, and left align it on screens 640px and wider --><div class="text-center sm:text-left"></div>

因此,通常最好先为设计实现移动端布局,然后再逐步添加适合 sm 屏幕的更改,再接着是 md 屏幕的更改,依此类推。

🌐 For this reason, it's often a good idea to implement the mobile layout for a design first, then layer on any changes that make sense for sm screens, followed by md screens, etc.

针对断点范围(Targeting a breakpoint range)

默认情况下,由类似 md:flex 的规则应用的样式将在该断点处生效,并会在更大的断点上继续生效。

🌐 By default, styles applied by rules like md:flex will apply at that breakpoint and stay applied at larger breakpoints.

如果你只想在特定的断点范围内应用某个工具类,可以将响应式变体如 mdmax-* 变体叠加,限制该样式只在特定范围内生效:

🌐 If you'd like to apply a utility only when a specific breakpoint range is active, stack a responsive variant like md with a max-* variant to limit that style to a specific range:

HTML
<div class="md:max-xl:flex">  <!-- ... --></div>

Tailwind 为每个断点生成相应的 max-* 变体,因此默认情况下可以使用以下变体:

🌐 Tailwind generates a corresponding max-* variant for each breakpoint, so out of the box the following variants are available:

变体媒体查询
max-sm@media (宽度 < 40rem) { ... }
max-md@media (宽度 < 48rem) { ... }
max-lg@media (宽度 < 64rem) { ... }
max-xl@media (宽度 < 80rem) { ... }
max-2xl@media (宽度 < 96rem) { ... }

针对单个断点(Targeting a single breakpoint)

要定位单个断点,通过将响应式变体如 md 与下一个断点的 max-* 变体叠加,来针对该断点的范围进行设置:

🌐 To target a single breakpoint, target the range for that breakpoint by stacking a responsive variant like md with the max-* variant for the next breakpoint:

HTML
<div class="md:max-lg:flex">  <!-- ... --></div>

阅读有关定位断点范围的内容以了解更多信息。

🌐 Read about targeting breakpoint ranges to learn more.

使用自定义断点(Using custom breakpoints)

自定义主题(Customizing your theme)

使用 --breakpoint-* 主题变量来自定义你的断点:

🌐 Use the --breakpoint-* theme variables to customize your breakpoints:

app.css
@import "tailwindcss";@theme {  --breakpoint-xs: 30rem;  --breakpoint-2xl: 100rem;  --breakpoint-3xl: 120rem;}

这会将 2xl 断点更新为使用 100rem,而不是默认的 96rem,并创建新的 xs3xl 断点,可以在你的标记中使用:

🌐 This updates the 2xl breakpoint to use 100rem instead of the default 96rem, and creates new xs and 3xl breakpoints that can be used in your markup:

HTML
<div class="grid xs:grid-cols-2 3xl:grid-cols-6">  <!-- ... --></div>

请注意,始终使用相同的单位来定义断点非常重要,否则生成的工具可能会按意外顺序排序,导致断点类以意外的方式相互覆盖。

🌐 Note that it's important to always use the same unit for defining your breakpoints or the generated utilities may be sorted in an unexpected order, causing breakpoint classes to override each other in unexpected ways.

Tailwind 使用 rem 作为默认断点,因此如果你要在默认断点上添加额外的断点,请确保也使用 rem

🌐 Tailwind uses rem for the default breakpoints, so if you are adding additional breakpoints to the defaults, make sure you use rem as well.

主题文档中了解更多关于自定义主题的信息。

🌐 Learn more about customizing your theme in the theme documentation.

删除默认断点(Removing default breakpoints)

要移除默认断点,请将其值重置为 initial 关键字:

🌐 To remove a default breakpoint, reset its value to the initial keyword:

app.css
@import "tailwindcss";@theme {  --breakpoint-2xl: initial;}

你也可以使用 --breakpoint-*: initial 重置所有默认断点,然后从头定义你所有的断点:

🌐 You can also reset all of the default breakpoints using --breakpoint-*: initial, then define all of your breakpoints from scratch:

app.css
@import "tailwindcss";@theme {  --breakpoint-*: initial;  --breakpoint-tablet: 40rem;  --breakpoint-laptop: 64rem;  --breakpoint-desktop: 80rem;}

主题文档中了解更多关于移除默认主题值的信息。

🌐 Learn more removing default theme values in the theme documentation.

使用任意值(Using arbitrary values)

如果你需要使用一个一次性的断点,而这个断点不适合包含在你的主题中,可以使用 minmax 变体,通过任意值即时生成自定义断点。

🌐 If you need to use a one-off breakpoint that doesn’t make sense to include in your theme, use the min or max variants to generate a custom breakpoint on the fly using any arbitrary value.

<div class="max-[600px]:bg-sky-300 min-[320px]:text-center">  <!-- ... --></div>

arbitrary values 文档中了解有关任意值支持的更多信息。

🌐 Learn more about arbitrary value support in the arbitrary values documentation.

容器查询(Container queries)

什么是容器查询?(What are container queries?)

容器查询 是一种现代 CSS 功能,它允许你根据父元素的大小而不是整个视口的大小来设置样式。它们使你能够构建更具可移植性和可重用性的组件,因为组件可以根据实际可用的空间进行调整。

基本示例(Basic example)

使用 @container 类将一个元素标记为容器,然后使用诸如 @sm@md 等变体根据容器的大小来设置子元素的样式:

🌐 Use the @container class to mark an element as a container, then use variants like @sm and @md to style child elements based on the size of the container:

HTML
<div class="@container">  <div class="flex flex-col @md:flex-row">    <!-- ... -->  </div></div>

就像断点变体一样,容器查询在 Tailwind CSS 中是移动优先的,并应用于目标容器大小及以上。

🌐 Just like breakpoint variants, container queries are mobile-first in Tailwind CSS and apply at the target container size and up.

最大宽度容器查询(Max-width container queries)

使用类似 @max-sm@max-md 的变体,在特定容器尺寸以下应用样式:

🌐 Use variants like @max-sm and @max-md to apply a style below a specific container size:

HTML
<div class="@container">  <div class="flex flex-row @max-md:flex-col">    <!-- ... -->  </div></div>

容器查询范围(Container query ranges)

将常规容器查询变体与最大宽度容器查询变体堆叠以定位特定范围:

🌐 Stack a regular container query variant with a max-width container query variant to target a specific range:

HTML
<div class="@container">  <div class="flex flex-row @sm:@max-md:flex-col">    <!-- ... -->  </div></div>

命名容器(Named containers)

对于使用多个嵌套容器的复杂设计,你可以使用 @container/{name} 为容器命名,并使用 @sm/{name}@md/{name} 等变体来针对特定容器:

🌐 For complex designs that use multiple nested containers, you can name containers using @container/{name} and target specific containers with variants like @sm/{name} and @md/{name}:

HTML
<div class="@container/main">  <!-- ... -->  <div class="flex flex-row @sm/main:flex-col">    <!-- ... -->  </div></div>

这使得可以根据远处容器的大小(而不仅仅是最近的容器)来设置样式。

🌐 This makes it possible to style something based on the size of a distant container, rather than just the nearest container.

使用自定义容器大小(Using custom container sizes)

使用 --container-* 主题变量来自定义容器大小:

🌐 Use the --container-* theme variables to customize your container sizes:

app.css
@import "tailwindcss";@theme {  --container-8xl: 96rem;}

这增加了一个新的 8xl 容器查询变体,可在你的标记中使用:

🌐 This adds a new 8xl container query variant that can be used in your markup:

HTML
<div class="@container">  <div class="flex flex-col @8xl:flex-row">    <!-- ... -->  </div></div>

主题文档中了解更多关于自定义主题的信息。

🌐 Learn more about customizing your theme in the theme documentation.

使用任意值

对于不想添加到主题中的一次性容器查询尺寸,使用类似 @min-[475px]@max-[960px] 的变体:

🌐 Use variants like @min-[475px] and @max-[960px] for one-off container query sizes you don't want to add to your theme:

HTML
<div class="@container">  <div class="flex flex-col @min-[475px]:flex-row">    <!-- ... -->  </div></div>

使用容器查询单元(Using container query units)

使用 容器查询长度单位cqw 作为其他工具类中的任意值来引用容器尺寸:

🌐 Use container query length units like cqw as arbitrary values in other utility classes to reference the container size:

HTML
<div class="@container">  <div class="w-[50cqw]">    <!-- ... -->  </div></div>

容器大小参考(Container size reference)

默认情况下,Tailwind 包含的容器尺寸范围从 16rem(256px)到 80rem(1280px):

🌐 By default, Tailwind includes container sizes ranging from 16rem (256px) to 80rem (1280px):

VariantMinimum widthCSS
@3xs16rem (256px)@container (width >= 16rem) { … }
@2xs18rem (288px)@container (width >= 18rem) { … }
@xs20rem (320px)@container (width >= 20rem) { … }
@sm24rem (384px)@container (width >= 24rem) { … }
@md28rem (448px)@container (width >= 28rem) { … }
@lg32rem (512px)@container (width >= 32rem) { … }
@xl36rem (576px)@container (width >= 36rem) { … }
@2xl42rem (672px)@container (width >= 42rem) { … }
@3xl48rem (768px)@container (width >= 48rem) { … }
@4xl56rem (896px)@container (width >= 56rem) { … }
@5xl64rem (1024px)@container (width >= 64rem) { … }
@6xl72rem (1152px)@container (width >= 72rem) { … }
@7xl80rem (1280px)@container (width >= 80rem) { … }
TailwindCSS 中文网 - 粤ICP备13048890号