Calmcode - tailwind: conditional classes

Conditional Classes

1 2 3 4 5 6 7

Consider the following HTML page with all the attached tailwind classes.

<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
  <div class="bg-yellow-200 p-4 m-4">
    <h1 class="text-lg sm:text-4xl md:text-6xl font-bold pb-4">
      Hello world.
    </h1>
    <p class="hidden md:block text-lg text-gray-400 bg-slate-200 p-6">
      This is a Tailwind CSS example.
    </p>
    <p class="text-lg text-gray-400 bg-slate-800 p-6">
      This another Tailwind CSS example.
    </p>
   </div>
</body>
</html>

Notice how there are some elements with hidden md:block classes. These classes are used to hide the element on smaller screens. The hidden class is used to hide the element on all screens and the md:block class is used to show the element on medium screens and above.

There is something similar happening with the text-lg sm:text-4xl md:text-6xl classes. These classes are used to set the text size. The text-lg class is used to set the text size to large on all screens. The sm:text-4xl class is used to set the text size to extra large on small screens and above. The md:text-6xl class is used to set the text size to extra extra large on medium screens and above.

This is a general pattern in tailwindcss. You can add classes to elements that will only be applied under certain conditions with usually follow the <condition>:<effect> syntax. This can be very useful to make your website responsive without having to write any JavaScript.