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"  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Center an Image Horizontally and Vertically Inside a Div- Tutorial Example</title> 

</head> 
<body> 
<div class="container">
<img src="https://www.tutorialexample.com/wp-content/uploads/2019/07/logo.ico" /> 
</div>
<div style="clear:both;"></div>
</body> 
</html>

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;}
</style>

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%);}
</style>

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

Notice:

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%;}

Leave a Reply

Your email address will not be published. Required fields are marked *