How to Center an Image in HTML

How to Center an Image in HTML

When working with HTML, you may want to center an image on your webpage. There are several ways to achieve this, depending on the layout and design of your website. In this article, we will explore different methods to center an image in HTML.

Method 1: Using the <center> Tag

You can center an image on a webpage by enclosing it within a <center> tag. This method is simple and straightforward.

<!DOCTYPE html>
<html>
<head>
    <title>Center Image</title>
</head>
<body>
    <center>
        <img src="https://how2html.com/wp-content/themes/dux/img/logo.png" alt="Centered Image" />
    </center>
</body>
</html>

Output:

How to Center an Image in HTML

Method 2: Using CSS

Another way to center an image is by using CSS. You can set the image’s margin to auto and display it as a block element to achieve this.

<!DOCTYPE html>
<html>
<head>
    <title>Center Image</title>
    <style>
        img {
            display: block;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <img src="https://how2html.com/wp-content/themes/dux/img/logo.png" alt="Centered Image" />
</body>
</html>

Output:

How to Center an Image in HTML

Method 3: Using Flexbox

Flexbox is a modern CSS layout model that makes it easy to center elements on a page. You can use flex properties to center an image horizontally and vertically.

<!DOCTYPE html>
<html>
<head>
    <title>Center Image</title>
    <style>
        .container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }
        img {
            max-width: 100%;
            max-height: 100%;
        }
    </style>
</head>
<body>
    <div class="container">
        <img src="https://how2html.com/wp-content/themes/dux/img/logo.png" alt="Centered Image" />
    </div>
</body>
</html>

Output:

How to Center an Image in HTML

Method 4: Using Table

You can also center an image using a table layout in HTML. By placing the image within a table cell and setting the cell’s alignment properties, you can achieve centering.

<!DOCTYPE html>
<html>
<head>
    <title>Center Image</title>
</head>
<body>
    <table>
        <tr>
            <td align="center">
                <img src="https://how2html.com/wp-content/themes/dux/img/logo.png" alt="Centered Image" />
            </td>
        </tr>
    </table>
</body>
</html>

Output:

How to Center an Image in HTML

Conclusion

In this article, we have explored various methods to center an image in HTML. Whether you prefer using the <center> tag, CSS, Flexbox, or a table layout, there are multiple ways to achieve the desired result. Experiment with these techniques to find the best approach for your website design.

Like(0)

HTML Articles