- Instant help with your CSS coding problems

Center an absolute element in TailwindCSS

Question:
How to center an absolute element in TailwindCSS?
Answer:
<div class="bg-slate-200 w-[600px] h-[400px] relative">
    <div class="absolute w-32 h-32 bg-amber-500 m-auto left-0 right-0 top-0 bottom-0">
        Absolute
    </div>
</div>
Description:

There are multiple ways to center absolute positioned elements using TailwindCSS. One of the most important step is to have the right wrapper / parent element relative using the class relative .

The next question is whether the element size is fixed.

Centering fixed size absolute element

To center an absolutely positioned element in TailwindCSS set the margin to auto using m-auto. Besides this, set top, bottom, left and right positions to 0 using top-0 , bottom-0 , left- 0 and right-0 classes and the browser selects a suitable margin to use. This is the simplest solution, but only works if the absolute positioned element has fixed width and height values.

<div class="bg-slate-200 w-[600px] h-[400px] relative">
    <div class="absolute w-32 h-32 bg-amber-500 m-auto left-0 right-0 top-0 bottom-0">
        Absolute
    </div>
</div>

And the result is:

Centering absolute div with fixed dimensions

Centering variable size absolute element

If you don't know the size of the element you want to center, or you don't want to set it to a fixed size, the above solution will not work.

In this case you need to use top and left positioning and translateX ans translateY. Using the top-1/2 and left-1/2 classes we set the element top-left corner to the center of the parent (relative) element. However, we do not want to center the top left corner, but the whole element. Therefore, we use the translateX and translateY CSS properties to offset the element. Both horizontally and vertically by half the current size using Tailwind utilities: -translate-x-1/2 and -translate-y-1/2 .

<div class="bg-slate-200 w-[600px] h-[400px] relative flex">
    <div  class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-amber-500 p-4">
        Absolute
    </div>
</div>

And the result is:

 

Share "How to center an absolute element in TailwindCSS?"
Interesting things
OpanAi's ChatGPT