![]() |
VOOZH | about |
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.
Table of Content
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:
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:
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:
Note: In above code, we can use justify-content: center; to align image Horizontally.
CSS Grid Layout provides another way to center elements both horizontally and vertically. The container is made a grid container with display: grid;.
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: