Skip to content

narrow screen priority and using a breakpoint

First, make the narrow screen styles, then use a breakpoint to match a (compare) wide screen and overwrite the style.

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="..." />

requirement

Make sure that the viewport meta element has been added to <html>:

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

Breakpoint

There are five breakpoints by default in TailwindCSS.

Breakpoint prefixMinimum widthCSS
sm40rem (640px)@media (width >= 40rem)
md48rem (768px)@media (width >= 48rem)
lg64rem (1024px)@media (width >= 64rem)
xl80rem (1280px)@media (width >= 80rem)
2xl96rem (1536px)@media (width >= 96rem)

配合 max—* 可定义生效范围

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

https://tailwindcss.com/docs/responsive-design#targeting-a-breakpoint-range

自定义断点

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

@theme 咱们放在进阶使用讲解,暂时就当成 Tailwind 的配置项理解吧。

ts
@import "tailwindcss";
@theme {
  --breakpoint-xs: 30rem; //用相同的单位(也就是rem,tailwind框架内部用的也是这个)来定义断点非常重要。混用单位的话,不小心冲突了样式就会打架。
  --breakpoint-2xl: 100rem;
  --breakpoint-3xl: 120rem;
}

↑ 这段代码将 2xl 断点从默认的 96rem 改为使用 100rem,并创建了新的 xs 和 3xl 断点,可在您的 html 代码中使用:

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

移除默认断点

将其值重置为 initial 即可

ts
@import "tailwindcss";
@theme {
  --breakpoint-2xl: initial;
}

可以使用 --breakpoint-*: initial 重置所有的默认断点,然后自行定义所有断点:

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