Tailwind CSS: Responsive design in Tailwind

With Tailwind CSS, it’s the same principle. But instead of writing a media query, we add a class to the HTML.

For example, suppose we want to build a responsive Grid layout.

We want it to have 1 column on small screens, 2 columns on the screen or laptop, and 3 columns on a big desktop screen.

Here’s what we do.

Let’s start with the Tailwind CSS starting template on Codepen.

Fork that.

We define the HTML adding the grid class to enable the Grid layout:

<div class="grid">
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
</div>

This automatically uses a 1 column layout.

Untitled

Now we use the sm: modifier and add sm:grid-cols-2 to apply two columns starting from screens of sm size:

<div class="grid sm:grid-cols-2">
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
</div>

You will see 2 columns if the window is large enough:

Untitled

Now add

<div class="grid sm:grid-cols-2 md:grid-cols-3">
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
  <p>Column</p>
</div>

You will see 3 columns making the window larger:

Untitled

Full example on Codepen

We have the following prefixes, called breakpoints:

PrefixMinimum width
sm640px
md768px
lg1024px
xl1280px
2xl1536px

Those prefixes can be applied to any Tailwind class.

It’s important to realize any Tailwind class by default is applied to all sizes.

Using a breakpoint prefix will only apply that class to screen sizes bigger than the one specified in the table.

So bg-black applies that background all the time, sm:bg-black only applies the black background if the screen is bigger than 640px.

Lessons in this unit:

0: Introduction
1: Box model properties
2: Colors
3: Typography
4: Flexbox and Grid in Tailwind
5: Modifiers
6: ▶︎ Responsive design in Tailwind
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!