Center image vertically and horizontally inside a div with a float: left?

I need a working solution to perform the three-sided task of centering images with different sizes, to a square div, when float: left is used to place images in rows.I use a div inside a div to do the trick:

 .outer-element{ //wrap tile div
     display:table-cell;
     width:300px;height:300px;
     text-align:center ;
     vertical-align:middle ;
     float:left;
     margin-bottom:15px;
 }
 .inner-element{ //div with image inside
     display:inline-block;
 }

BUT I have to use use float: left for the outer element to put the images in rows, and when the images are not centered vertically (they are aligned on the top border of the div), I tried some other CSS codes, but float: left always makes the images not vertically centered.

+5
source share
3 answers

float:left; .outer-element, , . , .outer-element , .

HTML

<div class="fl">
    <div class="outer-element">
        <div class="inner-element">
            <img src="http://thecybershadow.net/misc/stackoverflow.png" />
        </div>
    </div>
</div>

CSS

.fl {float:left;}
.outer-element{
    display:table-cell;
    width:300px;
    height:300px;
    vertical-align:middle;
    background:#666;
    text-align:center;
    margin-bottom:15px;
}
.inner-element{
    display:inline-block;
}

Exmaple: http://jsfiddle.net/xQEBH/17/

, !

+14

http://jsfiddle.net/aEfwC/

<div align="center">
    <div class="outer-element">
    <div class="image"></div>
</div>   
</div>


.outer-element
{
     width:300px;height:300px;
     float:left;
     background-color:#2a2a2a;
    position:relative;
 }
.image
{
width:128px;
height:128px;
background:url(http://thecybershadow.net/misc/stackoverflow.png);
vertical-align:middle; 
background-repeat:no-repeat;
}
0

Your css ...

.outer-element{ //wrap tile div
     display:table-cell;
     width:300px;height:300px;
     text-align:center ;
     vertical-align:middle ;
     float:left;
     margin-bottom:15px;
 }
.inner-element{ //div with image inside
     display:inline-block;
 }

Just add the following that you want your elements to float on the left ...

.outer-element:before{content: "."; height: 0; overflow: hidden; visibility: hidden; float: left;}

Hope this helps ...

0
source

All Articles