How to Center Image in HTML: Simple Methods Explained
To center an image in HTML, wrap the
<img> tag inside a container and use CSS with display: flex; justify-content: center; on the container. Alternatively, use text-align: center; on the container if it is a block element like <div>.Syntax
To center an image, place the <img> inside a container element like <div>. Then apply CSS to the container:
- Flexbox method: Use
display: flex;andjustify-content: center;to center horizontally. - Text-align method: Use
text-align: center;on the container to center inline elements like images.
html
<div style="display: flex; justify-content: center;"> <img src="image.jpg" alt="Example"> </div>
Output
An image centered horizontally inside a container.
Example
This example shows how to center an image horizontally using the flexbox method. The image is placed inside a <div> with CSS that centers it.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Center Image Example</title> <style> .center-container { display: flex; justify-content: center; margin-top: 2rem; } img { max-width: 100%; height: auto; border: 2px solid #333; } </style> </head> <body> <div class="center-container"> <img src="https://via.placeholder.com/200" alt="Placeholder Image"> </div> </body> </html>
Output
A 200x200 placeholder image centered horizontally on the page with a border.
Common Pitfalls
Common mistakes when centering images include:
- Applying
text-align: center;directly to the<img>tag, which has no effect because images are inline elements but need a block container. - Using margin auto on the image without setting
display: block;, which prevents centering. - Not setting a container width or using inline styles that conflict with centering.
Correct way to center with margin auto:
html
<!-- Wrong way: margin auto without display block --> <img src="image.jpg" alt="" style="margin: auto;"> <!-- Right way: display block and margin auto --> <img src="image.jpg" alt="" style="display: block; margin: 0 auto;">
Output
The first image will not center; the second image will be centered horizontally.
Quick Reference
| Method | CSS to Apply | Notes |
|---|---|---|
| Flexbox | display: flex; justify-content: center; | Centers image inside container horizontally |
| Text-align | text-align: center; | Works if image is inline inside block container |
| Margin Auto | display: block; margin: 0 auto; | Centers block image horizontally |
| Legacy (not recommended) | <center> tag or deprecated attributes | Avoid using deprecated HTML tags |
Key Takeaways
Wrap your image in a container and use CSS on the container to center it.
Use flexbox with justify-content: center for modern, reliable centering.
text-align: center works if the image is inline inside a block container.
For margin auto centering, set the image to display: block first.
Avoid deprecated HTML tags like for centering images.