Images are part of every web page in modern web design. As they are everywhere, it’s good to know how to style them perfectly on the page. You surely have faced situations where you need to center an image using TailwindCSS. Here are 2 simple ways to center an image.
Method 1: Using Margin to Center an Image
By default, images are set to display:block
in TailwindCSS. As they become a block-level element, you can use the margin
to center them on a web page. Here is the simple code to center an image vertically in TailwindCSS. You can also check the working example on tailwind playground.
1 2 3 4 5 6 7 |
<div class="h-screen bg-gray-200"> <img src="https://placekitten.com/200" class="mx-auto"> </div> |
Method 2: Using Flexbox to Center an Image
The first method will only work if you want to center the image vertically but you can use flexbox
to center vertically and horizontally. For this, you need a parent container with classes flex justify-center items-center
. The following code uses flexbox container to center an image with TailwindCSS. The output is attached as a screenshot below and you can check the working example online on tailwind playground.
1 2 3 4 5 6 7 |
<div class="flex h-screen w-full bg-blue-400 justify-center items-center"> <img src="https://placekitten.com/200"> </div> |
Conclusion
There are 2 simple ways to center an image in TailwindCSS. The first method is to use margin
and the second is to use flexbox
. Both these methods are for different use cases for vertically center align images, first method is good to center images vertically and horizontally, use the second method. You can also check how to center a div in TailwindCSS.