Responsive Design with Breakpoints
Using sm:, md:, and lg: prefixes to change styles at different viewport widths, mobile-first.
阅读需 2 分钟
Every utility class in Tailwind can be made conditional on viewport width by adding a breakpoint prefix — no separate media query block required.
<div class="text-center md:text-left">
<h2 class="text-xl md:text-3xl">Welcome back</h2>
</div>text-center applies at all widths by default; md:text-left overrides it to left-aligned once the viewport reaches the md breakpoint (768px by default) and up. Read md:text-left as "at md and wider, use text-left" — not "only at exactly md."
Mobile-first, not desktop-first
This is the detail that trips people up coming from plain CSS: an unprefixed utility applies at every width, and a prefixed one only overrides it from that breakpoint upward. That means you should design for the smallest screen first and layer on prefixed overrides as the viewport grows — not the other way around.
<!-- Correct: base styles are mobile, md: and lg: add changes for wider screens -->
<div class="flex flex-col gap-4 md:flex-row lg:gap-8">
<!-- Wrong intent: this doesn't mean "large screens only" -->
<div class="lg:flex">That second example doesn't hide the flex layout below lg — it simply does nothing below lg, and whatever display the element had by default (likely block) applies there instead. If you actually want different layouts at different sizes, you specify the base case explicitly, e.g. flex flex-col lg:flex-row.
The default breakpoints
| Prefix | Minimum width |
|---|---|
| sm: | 640px |
| md: | 768px |
| lg: | 1024px |
| xl: | 1280px |
| 2xl: | 1536px |
These are deliberately round numbers meant to catch common device categories (phone, tablet, laptop, desktop) rather than targeting exact devices — Tailwind's philosophy is to design against ranges of space, not specific hardware, since screen sizes vary more than any fixed list of devices could capture.
A realistic example
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
<div class="rounded-lg bg-white p-4 shadow">Card</div>
<div class="rounded-lg bg-white p-4 shadow">Card</div>
<div class="rounded-lg bg-white p-4 shadow">Card</div>
<div class="rounded-lg bg-white p-4 shadow">Card</div>
</div>One column on a phone, two on a tablet, four on a desktop — three layout decisions, expressed as three classes, with no media query written by hand and no separate CSS file to maintain per breakpoint.
Any utility, any breakpoint
There's no special list of "responsive-friendly" utilities — every single class in Tailwind, including ones you'll define yourself later via theme customization, automatically works with every breakpoint prefix. That consistency is what makes responsive design feel like a natural extension of the utility system rather than a separate skill to learn on top of it.