Image Centering in CSS
? How to Center Images in CSS
Centering an image is a common task and there are several ways depending on whether you want to center it horizontally, vertically, or both inside a container.
1. Center Image Horizontally (Block element)
Make the image a block-level element and use margin: auto:
img { display: block; margin-left: auto; margin-right: auto; /* or simply margin: 0 auto; */}2. Center Image Horizontally with Flexbox
If the image is inside a container, use flexbox on the container:
.container { display: flex; justify-content: center; /* centers horizontally */}<div class="container"> <img src="image.jpg" alt="Centered Image"></div>3. Center Image Vertically and Horizontally with Flexbox
.container { display: flex; justify-content: center; /* horizontal */ align-items: center; /* vertical */ height: 300px; /* container height needed */}4. Center Image Vertically and Horizontally with Grid
.container { display: grid; place-items: center; /* shorthand for align-items and justify-items */ height: 300px;}5. Center Image with Absolute Positioning
.container { position: relative; height: 300px;}img { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);}Summary Table
| Method | Horizontal Centering | Vertical Centering | Requires Container Height? |
|---|---|---|---|
margin: auto + block | ? | ? | No |
Flexbox (justify-content) | ? | ? (with align-items) | Yes |
CSS Grid (place-items) | ? | ? | Yes |
| Absolute + Transform | ? | ? | Yes |
If you want, I can generate a full example with HTML + CSS to demonstrate these!