Tailwind CSS: Align an element to the left/right of its parent
In Tailwind CSS, you can align a child element to the left or right side of its parent div by using the mr-auto or ml-auto utility class, respectively (we also add the flex utility to the parent). This technique works well in both these situations:
- The parent contains only a single child
- The parent contains multiple child elements
An alternative way to achieve your goal is to use the float-left and float-right utilities (I personally prefer flex to float, but the choice is totally up to you).
For more clarity, let’s see the practical examples below.
<body class="p-10"> <div class="bg-sky-300 w-full"> <div class="bg-amber-300 w-48 h-48 ml-auto p-10">Align Right</div> </div> </body>
This example does the something but with float-right.
<body class="p-10"> <div class="bg-green-500 w-full block"> <div class="bg-amber-300 w-48 h-48 float-right p-10">Float Right</div> <div class="clear-both"></div> </div> </body>
That’s it. Continue learning more by taking a look at the following articles:
- How to Create Semi Circles in Tailwind CSS
- Tailwind CSS: Create Buttons with Text and Icons Inside
- Tailwind CSS: Align a child element to the bottom of its parent
- Tailwind CSS: How to Create a Skewed Card
- Tailwind CSS: Make a Child Element Fill the Remaining Space
- Tailwind CSS: How to Create a Sticky/Affix NavBar
You can also check out our CSS category page for the latest tutorials and examples.