Responsive Design with Tailwind
In plain CSS, responsive design can be a complicated tangle of CSS classes and @media
tags. Tailwind provides prefixes that can be applied to any Tailwind utility to control the set of screen sizes.
Tailwind Screen Widths and Breakpoints
In CSS, various properties may be applied conditionally based on the width of the screen. These conditions are managed with the @media
tag. The specific screen widths at which the design changes are often called breakpoints. In Tailwind, you can put a prefix on any Tailwind utility to specify the minimum screen width where that utility should be applied.
Tailwind defines five screen widths by default:
- Small (
sm:
)—640 pixels and up - Medium (
md:
)—768 pixels and up - Large (
lg:
)—1024 pixels and up - Extra large (
xl:
)—1280 pixels and up - Extra extra large (
2xl:
)—1536 pixels and up
The idea is that you’ll define your design for mobile devices first, and then use the prefixes to adjust the design for larger screens.
Hide Based on Size
One way to make your application fit on a smaller screen is by hiding parts of the user interface on the smaller screen. In this case, because the smallest screen behavior is hidden, the unprefixed property is .hidden
. At larger sizes, you might want the item to display, so you add in .lg:block
(or whatever breakpoint you want to start seeing the item at), winding up with class="hidden lg:block"
.
It’s quite common to have an element for a hamburger menu replace a navigation bar on small screens, but then disappear on a device that’s large enough to show all the navigation. In that case, the small-size behavior is to display, which is the default, and you add the hiding behavior as a breakpoint, like class="lg:hidden"
.
Another step for responsive designs is to use fewer Grid Columns on small devices and flex on larger devices.