How to create responsive HTML elements using Tailwind CSS

Creating responsive web designs has become very easy using Tailwind CSS. Here we will demonstrate with a simple example.

1. Show in PC, Hide in Phones

See the below example,

<div class="hidden md:flex"> This div is visible only to PC </div>

This div will be visible only on larger screens since we have mentioned hidden by default. That means starting from smaller(sm) device this div will be hidden.


Then we add the breakpoint md:(medium devices) and attach a display property flex to this breakpoint.

md:flex
This means from medium size screens this div will be visible. But it will be hidden in smaller devices like phones.

2. Show in Phones, Hide in PCs

Now, to show the div only to smaller devices use this,

<div class="flex md:hidden"> This div is visible only to Phone </div>

This div will be visible in all device until it meets the breakpoint md: and from that point onwards it becomes invisible and hence is not visible on larger screens.

Notes:

  1. Tailwind uses Mobile-First approach - unless you specify a breakpoint, the css class will be applied to all devices.

    Which means classes like `uppercase` will be applied to all screen sizes, while prefixed utilities (like `md:uppercase`) only take effect at the specified breakpoint and above!

  2. To Target Mobile Screens Don't use `sm:` instead use unprefixed utilities like `font-bold`.

    Don’t think of sm: as meaning “on small screens”, think of it as “at the small breakpoint“.

    For example,

    <!-- This will center text on mobile, and left align it on screens 640px and wider -->
              <div class="text-center sm:text-left"></div>