How to Center an Image with CSS

This post originated from our #WhiteboardWednesdays social media campaign on Instagram. Follow Us @Inforestcom

Horizontally Centering an Image

Method 1

The Text-Align Center method uses a wrapper and text-align: center properties. This is an older method. I’ve seen various discussions on whether this is proper mark up or not

.wrapper {
    text-align: center;
}

<div class="wrapper"><img src="inforest.jpg" alt="Inforest"></div>

Method 2

The Margin Auto Method Uses Display: Block and Margin:Auto to center the image

img.center { display: block; margin-left: auto; margin-right: auto; }

 <img src="inforest.jpg" alt="Inforest" class="center">  

Method 3

The Absolute Position Method uses absolute and relative positioning to center the image. *We find this to works best with images that have a fixed with

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

Flexbox is a newer utility package and is not supported by older browsers. Check out this neat guide for flexbox that includes a guide of supported browsers: Flexbox Guide

Using Flexbox to Vertically Center

.vcenter {
min-height: 12em;
display: table-cell;
vertical-align: middle;}

<div class="vcenter">
<img src="inforest.jpg" alt="Inforest"></div>

Perfect Centering using Flexbox