Vertical image center without dimensional knowledge

In my web development career, I have concentrated a lot of material, but I was wondering if there is an easy way to center the image vertically without knowing the size of the image. Imagine a list of thumbnails that I get from the database. I do not want each element to be at the top of the parent div.

<div id="wrapper">
    <div id="parent">
        <img src="path/i/got/from/database/image.png" />
    </div>
</div>
+5
source share
6 answers

You can use this CSS for your parent:

#parent {
    display:table-cell;
    vertical-align:middle;
}

Note that this will cause the parent to behave as an inline element.

An example .

+9
source

parent inline ( , Purmou, ), line-height parent height vertical-align: middle; img.

: http://jsfiddle.net/ThinkingStiff/YRGBk/

HTML:

<div id="wrapper">
    <div id="parent">
        <img src="http://placehold.it/200x200" />
    </div>
</div>

CSS

img {
    vertical-align: middle;
}

#parent {
    height:400px;
    border:1px solid black;
    line-height: 400px;
}

:

enter image description here

+4
#parent img{vertical-align:middle;}
+1

, , Javascript. , .

SPAN IMG-:

<div id="wrapper">
   <div id="parent">
      <span>&nbsp;</span><img src="path/i/got/from/database/image.png" />
   </div>
</div>

CSS :

#parent {
   height: 500px;      /* This height is important for the following lines */

   line-height: 500px; /* Text-content needs to get full height for the
                          'vertical-align'-attribute to work */
}
#parent span {
   display: inline-block; /* Should work even for IE6/7 in this case */

   height: 500px;         /* Needed for IE */

   width: 10px;
   margin-right: -10px;   /* Any element to the right is pushed to the left
                             offset of the SPAN-tag */ 
}
#parent img {
   vertical-align: middle; /* Aligns the image in the middle of the SPAN-tag */
}

IE6 7.

:

  • ThinkingStiffs , , . IE6.

  • IE6 7, .

0

I found this when looking for a solution to a similar problem, the solution uses CSS3, so it will not work on IE8 and below.

Although this is an old question, I decided that an updated answer might be useful to someone:

<div id="wrapper">
    <div id="parent">
        <img src="path/i/got/from/database/image.png">
    </div>
</div>

#parent{
    width:400px;
    height:400px;
    background:red; /* just used to highlight box */
    text-align:center;
}    
#parent img{
    position:relative;   
    top: 50%;
    transform: translateY(-50%);
}

See this script: http://jsfiddle.net/E9sTk/

0
source

You can use this:

#wrapper{    
height: 100%;
min-height: 500px;/*Assuming min-height of the container*/
position: relative;
width: 100%;}

#parent{    
border: 1px solid;
height: 50px;
position: absolute;
top: 50%;
width: 50px;}

Check it out in the script http://jsfiddle.net/kYgqx/2/

-1
source

All Articles