Center an image with CSS

Centering an image in CSS can be accomplished using the display: block property combined with margin: 0 auto. This technique works by making the image a block-level element and then applying automatic left and right margins.

Syntax

img {
    display: block;
    margin: 0 auto;
}

Method 1: Using Block Display and Auto Margins

The most common method to center an image horizontally is to set display: block and use margin: 0 auto

<!DOCTYPE html>
<html>
<head>
<style>
    .centered-image {
        display: block;
        margin: 0 auto;
        width: 300px;
        border: 2px solid orange;
        border-radius: 5px;
        padding: 10px;
    }
</style>
</head>
<body>
    <img src="/videotutorials/images/coding_ground_home.jpg" alt="Online Compiler" class="centered-image">
</body>
</html>
A centered image with an orange border, rounded corners, and padding appears horizontally centered on the page.

Method 2: Using Text Alignment

Another approach is to wrap the image in a container and use text-align: center

<!DOCTYPE html>
<html>
<head>
<style>
    .image-container {
        text-align: center;
        background-color: #f0f0f0;
        padding: 20px;
    }
    
    .image-container img {
        width: 250px;
        border: 3px solid #333;
        border-radius: 8px;
    }
</style>
</head>
<body>
    <div class="image-container">
        <img src="/videotutorials/images/coding_ground_home.jpg" alt="Online Compiler">
    </div>
</body>
</html>
A centered image with a dark border inside a light gray container with padding appears horizontally centered.

Method 3: Using Flexbox

Modern CSS flexbox provides an elegant solution for centering images both horizontally and vertically −

<!DOCTYPE html>
<html>
<head>
<style>
    .flex-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 400px;
        background-color: #e8f4fd;
    }
    
    .flex-container img {
        width: 200px;
        box-shadow: 0 4px 8px rgba(0,0,0,0.3);
        border-radius: 10px;
    }
</style>
</head>
<body>
    <div class="flex-container">
        <img src="/videotutorials/images/coding_ground_home.jpg" alt="Online Compiler">
    </div>
</body>
</html>
An image with rounded corners and shadow appears perfectly centered both horizontally and vertically within a light blue container.

Conclusion

The display: block with margin: 0 auto method is the most reliable for horizontal centering. Use flexbox when you need both horizontal and vertical centering, and text-align for simple inline centering within containers.

Updated on: 2026-03-15T12:52:22+05:30

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements