by in Developer Notes

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

Leave a Reply

You must be logged in to post a comment.

About Leon Rainbow

Leon is primary lead for Inforest Communications graphic and Web design services. He has over ten years experience in Web design and development and is proficient working with open­source CMS systems. He holds an associates degree in Computer Graphics from Mercer County Community College. Leon Rainbow is also a well known artist in Mercer County who creatively combines graffiti, street art and other artistic forms into innovative projects and events. He reaches out to wide audience, from galleries to the walls of inner cities. Leon curates two annual art festivals in New Jersey for area painters and the community as well as dedicating his civic duty to teaching after­school art programs in Trenton and Princeton, NJ.