align image at middle of div element


Posted on : Mon, 12th Oct 15 09:34 am (Updated on : Mon, 12th Oct 15 09:34 am) UTC
Author : Code2care
2314 votes

If you have an image inside a div element and you want it to be displayed exactly at the center of it then you must apply display=block, vertical-align=middle and text-align=center to that div.

Example : We have a div with width and height as 400px with an image located within it. If you do not add any css properties, the image will be displayed at the top-left corner of the div element.

center-align-image-div.html Language : Html
<html>
<head>
<title>Image displayed at top-left corner of the div</title>
<style>
.my-div {

    width:400px;
    height:400px;
    border:1px dotted #888;

}
</style>
</head>
<body>

<div class="my-div">
    <img src="http://code2care.org/tools/base64-decoder-encoder/images/code2care-logo.png" />
</div>

<body>
</html>

Output :

Image aligned at top-left corner of div element


Solution :

Css Code Snippet Language : CSS
.my-div {
    display:table-cell;
    vertical-align:middle;
    text-align:center;
    width:400px;
    height:400px;
    border:1px dotted #888;
    background:#fefefe;
    border-radius:15px
}

Output :

Image aligned at the center of the div


The image is now aligned at absolute center Vertically as well as Horizontally within the div element.

Browser Support test :

Property : text-align

  • IE : Internet Explorer 8 or above
  • Firefox : version 38 or above
  • Chrome : version 31 or above
  • Safari : version 8 or above

Property : vertical-align

It is supposed by all browsers : IE6+, Firefox 2+, Chrome 1+

Property : display

  • IE : Internet Explorer 8 or above
  • Firefox : version 38 or above
  • Chrome : version 31 or above
  • Safari : version 8 or above

Code2care's mission is to share varied knowledge in technical and non-technical areas gathered during day-to-day learnings and development activities so that our visitors can leverage this portal to find solutions to their queries without re-inventing the wheel. Technical posts include Learnings, Tutorials, Video Tutorials, Code Snippets, Tips-n-tricks.

Follow us : Facebook - Twitter - Google +