Lesson 9 +10 XP

Responsive Design

Responsive Design

Every utility can be applied conditionally at different breakpoints, making it easy to build responsive interfaces without leaving your HTML.

The viewport meta tag

Make sure your page has the viewport meta tag:

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

Breakpoint prefixes

Prefix any utility with a breakpoint name:

<img class="w-16 md:w-32 lg:w-48" src="..." />

There are five default breakpoints:

PrefixMin 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)

Mobile-first

Tailwind uses a mobile-first breakpoint system. Unprefixed utilities apply on all screens; prefixed ones apply at the breakpoint and above.

So to style something for mobile, use the unprefixed version:

<!-- Centers on mobile, left-aligns on 640px+ -->
<div class="text-center sm:text-left"></div>

Don't think of sm: as "on small screens" - think of it as "at the small breakpoint and up".

Targeting a range

Stack md with a max-* variant to target a range:

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

max-sm, max-md, max-lg, max-xl, max-2xl are all available.

Custom breakpoints

Add or change breakpoints in CSS with --breakpoint-*:

@theme {
  --breakpoint-xs: 30rem;
  --breakpoint-3xl: 120rem;
}

Container queries

Use @container to mark an element as a container, then style children based on the container size:

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

Container sizes range from @3xs (16rem) to @7xl (80rem).

TL;DR

  • sm, md, lg, xl, 2xl are the default breakpoints.
  • Tailwind is mobile-first: unprefixed = all screens.
  • Use max-* variants to target ranges.
  • @container enables container queries.