Advertisement
Advertisement


Align image in center and middle within div


Question

I have following div

<div id="over" style="position:absolute; width:100%; height:100%>
 <img src="img.png">
</div>

How to align the image so as to be located in the middle and center of div ?

2014/07/19
1
315
7/19/2014 12:11:13 AM


<div style="display:table-cell; vertical-align:middle; text-align:center">
<img src="img.png">
</div>
2011/02/03

This can also be done using the Flexbox layout:

STATIC SIZE

.parent {
    display: flex;
    height: 300px; /* Or whatever */
    background-color: #000;
}

.child {
    width: 100px;  /* Or whatever */
    height: 100px; /* Or whatever */
    margin: auto;  /* Magic! */
}
<div class="parent">
    <img class="child" src="https://i.vimeocdn.com/portrait/58832_300x300"/>
</div>

DYNAMIC SIZE

html, body {
  width: 100%;
  height: 100%;
  display: flex;
  background-color: #999;
}

* {
  margin: 0;
  padding: 0;
}

.parent {
  margin: auto;
  background-color: #000;
  display: flex;
  height: 80%;
  width: 80%;
}

.child {
  margin: auto;  /* Magic! */
  max-width: 100%;
  max-height: 100%;
}
<div class="parent">
  <img class="child" src="https://i.vimeocdn.com/portrait/58832_300x300"/>
</div>

I found the example in this article, which does a great job explaining the how to use layout.

2017/02/27

Seems to me that you also wanted that image to be vertically centered within the container. (I didn't see any answer that provided that)

Working Fiddle:

  1. Pure CSS solution
  2. Not breaking the document flow (no floats or absolute positioning)
  3. Cross browser compatibility (even IE6)
  4. Completely responsive.

HTML

<div id="over">
    <span class="Centerer"></span>
    <img class="Centered" src="http://th07.deviantart.net/fs71/200H/f/2013/236/d/b/bw_avlonas_a5_beach_isles_wallpaper_image_by_lemnosexplorer-d6jh3i7.jpg" />
</div>

CSS

*
{
    padding: 0;
    margin: 0;
}
#over
{
    position:absolute;
    width:100%;
    height:100%;
    text-align: center; /*handles the horizontal centering*/
}
/*handles the vertical centering*/
.Centerer
{
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
.Centered
{
    display: inline-block;
    vertical-align: middle;
}

Note: this solution is good to align any element within any element. for IE7, when applying the .Centered class on block elements, you will have to use another trick to get the inline-block working. (that because IE6/IE7 dont play well with inline-block on block elements)

2014/02/19

img.centered {
   display: block;
   margin: auto auto;
}
2018/05/26

You can do this easily by using display:flex css property

#over {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
2019/01/11

Source: https://stackoverflow.com/questions/4888223
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]