In TailwindCSS, centering an element may be a challenge for beginners if they don’t know the core concepts of CSS. You can center a div element easily using margin
or flex-box
in TailwindCSS but if you have an element that is positioned absolute
on the page, this will not work. Here are 2 methods to center an absolute
positioned element in TailwindCSS.
Method 1: Horizontally Centering an Absolute Positioned Element
You can make use of the margin
and left
, right
positioning to center an absolute
positioned element on the page. In this method, you have to set the margin
to auto
and then left
, right
to 0. Here is the example below.
1 2 3 4 5 6 7 8 |
<div class="h-screen"> <div class="absolute h-60 w-60 bg-red-600 m-auto left-0 right-0"> </div> </div> |
Here is the working code and you can check the output in the following screenshot.
Method 2: Horizontally and Vertically Centering an Absolutely Positioned Element
The above method will only center the element horizontally but will not do for vertical position. So, if you want to center the absolute
positioned element both vertically and horizontally, you need some additional classes. Here is an example that uses the translate properties to center an absolute
element both vertically and horizontally.
1 2 3 4 5 6 7 8 9 |
<div class="h-screen"> <div class="h-20 w-20 bg-red-600 right-0 absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2"> </div> </div> |
You can check the working example on the Tailwind playground.
Conclusion
You can center an absolutely positioned element using TailwindCSS by using 2 methods. In the first method, you can use of margin
, left
and right
classes to center the element horizontally. The second method is useful when you want to center the element in both the x
and y
directions. For the second method, you have to use the translate
properties in TailwindCSS.