To make this more tangible, we’ll use a basic example: the Hero section on a website. Let’s say that on desktop, we want our Hero section to have the image on the left, and the title, subtitle and main call to action button (or “CTA”) in a column to the right. And on mobile, we want the image on top and the three elements underneath it.
So on desktop, we have a row, with the image and text both taking up 50% of the widthand on mobile, we have a column, with the image and column both taking up 100% of the width.
How do we go ahead building that?
The first thing to note is that Tailwind, like every other CSS framework worth mentioning, is** mobile-first**. What does that mean?
It means that when we build the page, we define mobile behaviour as the rule, and behaviour on higher resolutions as the exception. Why is this? There are two reasons:
- The first is that over 60% of the traffic on the internet is on mobile screens; we need to ensure we cater properly to people on their phones
- The second is that designers and developers work on desktops, so catering to a mobile audience does not come naturally.
So we define the mobile behaviour as the normal behaviour and the layout for larger dimensions as the exception.
Let’s look at what this means for our "Hero Section”. We want our hero section to use a FlexBox column layout by default, and the image and text columns to both have a 100% width. And then, above a certain screen width, let’s say a tablet screen size, we want the container to use a FlexBox row layout and each element to take up 50% of its width.
How do we go about that in practice in Tailwind CSS?
To do that, we need to understand how Tailwind CSS handles class variants. These variants cover more than responsivity and screen size. They also allow you to define a hover behaviour, a dark mode variant and more.
To define these variants, we add a prefix and a colon. So, for example, to specify a behaviour on the hover, we'll write "hover:" and then the name of the class we want to activate on the hover. In the same way, to manage the "dark mode" directly in Tailwind, you have to create classes with the prefix "dark:".
Now, let's take the example of the subject we are interested in here, the management of "responsiveness". Tailwind has five breakpoints by default, which are:
smas in Small, which is 640 pixels wide
mdas Medium, which is 768 pixels wide
lgas Large, which is 1024 pixels wide,
xlas in 1280 pixels, and
2xlwhich is 1536 pixels.
All of this is, of course, customisable.
In Tailwind CSS, we have the classes
w-1/2, which mean a width of 100% and 50%. Let's say we want an element to be 100% wide on mobile and 50% wide on tablet screens.
In this case, we assign the classes
md:w-1/2 to the element. In other words: by default, a full width, and from the "breakpoint md", a width of 50%. And this is what we will use here to make the site responsive.