Center an Image Horizontally and Vertically Inside a Div Container: A Beginner Guide

By | November 20, 2019

When we are designing a site theme, we often need to display images row by row, however, each image may have different width and height, how to display them in the center of a div horizontally and vertically? In this tutorial, we will tell you how to do.

Create an image in a css div

You can copy this code below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
<html xmlns=""> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Center an Image Horizontally and Vertically Inside a Div- Tutorial Example</title> 

<div class="container">
<img src="" /> 
<div style="clear:both;"></div>

In this code, we will display an image in a div with class name called ‘container‘.

Set the style of div container

<style type="text/css">  
.container {float:left;height:300px; width:300px;  position: relative; border:#999999 solid 1px;}

These properties are items you must set:

postion: you should set it to be relative

width and height: because we have floated this div, if you do not float it, you need not set width and height.

Set the style of image in div container

<style type="text/css"> 
.container img{position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);}

The css properties of the image in div must be set above.

We set the postion of this image to be absolute first, then we make the left corner of this image to the center of div container by top and left css property, finally, we transform the center of this image to the center of div container by transform property.

The effect of this code likes this:

center image horizontally and vertically in a div


When you are using this example code in tutorial, you should be sure the width and height of div container is bigger than the width and height of images.

If the width and height of images are bigger, you can set max-width and max-height css properties like this:

.container image{max-width:100%; max-height:100%;}