Hide Based on Size

Learn how to hide parts of applications to fit on a smaller screen.

Hiding elements for different screens

One way to make our 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. We might want the item to display at larger sizes, so we add in .lg:block, winding up with class="hidden lg:block".

Sometimes we may want to go the other way and display an element at a smaller size but not at a larger one. It’s quite common to have an element for a hamburger menu replace a navigation bar on the small size but then disappear on a device that is large enough to show all the navigation. In that case, the small-size behavior is to display, which is the default, and we add the hiding behavior in as a breakpoint, class="lg:hidden".

Similarly, it’s common to drop the size of header text on smaller devices. The lower size is the minimal width default, so the resulting DOM classes would look something like class="text-xl md:text-2xl lg:text-4xl".

Fewer grid columns on small devices

In general terms, the goal of a lot of responsive design is to simultaneously allow information to be stacked at small sizes and spread out into rows when the space exists at larger sizes. Exactly how we want to do this depends on our goal.

One possibility is that we have a set of card-like elements. This can look like the featured posts on a news site, where the data is not a table but a series of items laid out in a row.

In this case, we might want the items to fill the entire width of the screen but the number of items to vary based on the size of the screen. On a smartphone, we might want only one item across the screen while on a desktop, we might want four. So, we can use something like the following:

<div class="grid items-stretch
            md:grid-cols-2 md:gap-4
            lg:grid-cols-4 lg:gap-4">
  <div class="mb-6 lg:mb-0"></div>
  ... 
</div>

A couple of things to note here:

  • The parent div is a grid at all widths, but the default grid size at the narrowest width is 1, growing to 2 on a medium screen and to 4 on a large screen.
  • items-stretch means that each individual child element will stretch to fill its portion of the width, which means they will get bigger as the screen gets bigger until the next breakpoint, and then more items will be added to each row.
  • We also increase the gap between items as the screen gets bigger.
  • For the child items, we have the margin bottom mb-6 when only one element is in the row so that there is some spacing, but the margin bottom goes away when the screen gets larger, with lg:mb-0.

Get hands-on with 1200+ tech skills courses.