This tutorial aims to guide you on how to build flexible layouts using Flexbox utilities in Tailwind CSS. By the end of this tutorial, you will have a solid understanding of how to use Tailwind's utility classes to control layout, alignment, and sizing of website elements.
Tailwind CSS is a utility-first CSS framework with a lot of classes to help you build your UI. One of these classes is Flexbox, which makes it easy to design flexible responsive layout structure without using float or positioning.
To start using Flexbox in Tailwind, you need to add the flex
class to your parent container. This will set the display: flex;
property on the container.
<div class="flex">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
In this example, we will align items along the vertical and horizontal axis using the items-center
and justify-center
classes.
<div class="flex items-center justify-center h-screen">
<div class="p-5 bg-blue-500 text-white">Centered Item</div>
</div>
flex
: makes the container a flex container.items-center
: vertically aligns all children in the middle of the container.justify-center
: horizontally aligns all children in the middle of the container.h-screen
: sets the height of the container to be the same as the screen.p-5
: adds padding all around the child div.bg-blue-500
: sets the background color of the child div.text-white
: sets the text color in the child div.In this tutorial, you've learned how to build flexible layouts using Flexbox utilities in Tailwind CSS, how to align and size elements, and how to make your layout responsive. The next steps would be to use these techniques to build your own layouts. You can find more information on Tailwind's official documentation.
<div class="flex justify-center items-center h-screen">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
<div class="flex justify-between h-screen">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
</div>
<div class="flex flex-col sm:flex-row h-screen">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
In the third exercise, flex-col
makes the items stack vertically and sm:flex-row
makes them stack horizontally on small (sm) screens and above.