How to CSS Center Image Horizontally and Vertically
Centering images with CSS is a fundamental part of web design, but there are several techniques to achieve this depending on the layout you’re working with. Here’s a breakdown of some popular methods to CSS center image both horizontally and vertically:
This post originated from our #WhiteboardWednesdays social media series on Instagram. Follow us @Inforestcom for more tips!
Horizontally Centering an Image
Method 1: Text-Align Center
This classic method involves wrapping the image inside a container and applying text-align: center to the wrapper. While it’s considered an older approach and has sparked debate among developers regarding semantic HTML, it still works reliably in many scenarios to center using CSS horizontally.

.wrapper {
text-align: center;
}
<div class="wrapper"><img src="inforest.jpg" alt="Inforest"></div>
Method 2: Margin Auto
This is one of the most popular and modern techniques. By setting the image as display: block and applying margin: auto, you can easily CSS center image horizontally. This method is clean, simple, and widely supported.

img.center { display: block; margin-left: auto; margin-right: auto; }
<img src="inforest.jpg" alt="Inforest" class="center">
Method 3: Absolute Positioning
This technique uses a combination of position: absolute on the image and position: relative on the parent container. It’s ideal when you’re working with images that have a fixed width. This method provides precise control to center an image especially in more complex layouts.

img {
display: block;
position: relative;
left: -50%;
}
.wrapper {
position: absolute;
left: 50%;
}
<div class="wrapper">
<img src="inforest.jpg" alt="Inforest">
</div>
Vertically Centering an Image
When it comes to vertical alignment, modern CSS offers powerful solutions.
Method: Flexbox
Flexbox is a modern CSS module designed to align content easily. It allows you to center the image using CSS both horizontally and vertically with minimal code:

.vcenter {
min-height: 12em;
display: table-cell;
vertical-align: middle;}
<div class="vcenter">
<img src="inforest.jpg" alt="Inforest"></div>
Keep in mind, Flexbox may not be supported in very old browsers. For an in-depth look at compatibility, check out this helpful Flexbox Guide.
Conclusion
Whether you’re working with legacy code or building a modern responsive site, there’s always a way to CSS center image effectively. Choose the method that fits your project best, and keep your layout clean and user-friendly.
For more tips and tricks, don’t forget to follow us on Instagram at @Inforestcom and stay tuned for our next #WhiteboardWednesdays!