VOOZH about

URL: https://www.geeksforgeeks.org/html/how-to-center-an-image-in-html/

⇱ How to Center an Image in HTML? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Center an Image in HTML?

Last Updated : 23 Jul, 2025

To Center an image in HTML is a common task in web design, and there are several modern ways to do it using CSS. While the old <center> tag was once popular, it's now deprecated in HTML5. Today, nearly 80% of websites use CSS techniques like text-align,margin: auto, or flexboxto center images either horizontally, vertically, or both. In this article, you'll learn the best methods to center an image in a clean, modern way using HTML and CSS.

Horizontally Center an Image using CSS

1. Using text-align Property

The text-align property in CSS is used to center an image within a container element. By wrapping the image inside a div and applying text-align: center; to the container, the image gets aligned to the center of the page horizontally.

Example: Center an image using a container div with the text-align: center; CSS property.

Output:

πŸ‘ textAlign
use text align-property

2. Using CSS margin Property

To center an image is by using the margin property, you need to set the left and right margins of the image to auto. This works when the image as a block element. The browser will automatically adjust the space on either side to center it.

Example: In this example, we set image margin left & right to auto to center the image horizontally within its containing block.

Output:

πŸ‘ marginAuto
using margin: auto

Vertically Center an Image using CSS Flexbox

Vertically center an image can be more challenging than horizontal centering, but with modern CSS techniques like Flexbox and CSS Grid, it’s become easier and more flexible. Flexbox provides a more flexible way to center elements both horizontally and vertically. The container is made a flex container with display: flex.

Example: The align-items: center; place the image to centers vertically. The height: 100vh; style ensures the container takes up the full viewport height.

Output:

πŸ‘ vertically-align
Vertically center an Image



Note: In above code, we can use justify-content: center; to align image Horizontally.

Center an Image Horizontally & Vertically using CSS Grid Layout

CSS Grid Layout provides another way to center elements both horizontally and vertically. The container is made a grid container with display: grid;.

Syntax:

image_container {
display: grid;
place-items: center;
height: 100vh;
}

Example: The place-items: center; style centers the image both horizontally and vertically within the grid. The height: 100vh; style ensures the container takes up the full viewport height.

Output:

πŸ‘ centerBoth
center both vertically & horizontally
Comment
Article Tags:
Article Tags: