Centring with absolute positioning in TailwindCSS

If you’ve been using TailwindCSS, you’ll know that you can easily change the positioning of elements like this.

<div class="relative">
	<div class="absolute">
		How to position this?
	</div>
</div>

You can easily make your absolute positioned element cover it’s relative positioned parent, like this:

<div class="relative">
	<div class="absolute inset-0">
		I’ve covered my parent element.
	</div>
</div>

And you can use top-0 to position it at the top and there is left, right and bottom too.

But what if you want to centre the absolute element within the relative parent – both horizontally and vertically?

<div class="relative">
	<div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2">
		I’m centered horizontally and vertically!
	</div>
</div>

And that’s it – it’s really easy.

Share