Open In App

How to Center an Image using Tailwind CSS ?

Last Updated : 20 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are the methods to center an image using Tailwind CSS:

Method 1. Using Flexbox Classes

This method centers the image both horizontally and vertically using Tailwind's flex, justify-center, and items-center classes.

HTML
<html>
<head>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="h-screen flex items-center justify-center">
    <img src="https://media.geeksforgeeks.org/wp-content/uploads/20220221132017/download.png"
         alt="Centered Image" class="w-32 h-32">
</body>
</html>
  • The h-screen class sets the height of the body to 100% of the viewport height.
  • The flex class makes the body a flex container.
  • The items-center class centers the image vertically within the flex container.
  • The justify-center class centers the image horizontally within the flex container.
  • The w-32 and h-32 classes set the width and height of the image, respectively.

Method 2. Using Positioning Classes

This method uses Tailwind's absolute and transform utilities to center the image.

HTML
<html>
<head>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="relative h-screen">
    <img src="https://media.geeksforgeeks.org/wp-content/uploads/20220221132017/download.png"
         alt="Centered Image" 
         class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-32 h-32">
</body>
</html>
  • The relative class on the container establishes a positioning context.
  • The absolute class positions the image relative to the container.
  • The top-1/2 and left-1/2 classes position the image in the center.
  • The transform with -translate-x-1/2 and -translate-y-1/2 ensures the image is perfectly centered by adjusting its position based on its dimensions.

Method 3. Using Margin Auto for Horizontal Centering

To center an image horizontally within a block-level parent container, you can use the mx-auto class.

HTML
<html>
<head>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="h-screen flex items-start justify-center">
    <div class="w-1/2">
        <img src="https://media.geeksforgeeks.org/wp-content/uploads/20220221132017/download.png"
             alt="Centered Image" class="mx-auto w-32 h-32">
    </div>
</body>
</html>
  • The mx-auto class applies automatic margins on the left and right, centering the image horizontally within its parent.
  • Ensure the parent container has a defined width (w-1/2 in this case) for mx-auto to work effectively.

Next Article

Similar Reads