开发者

Vertically aligning an image in a div element?

I have a div element whose height I set with em, and whose width I set as a percentage. There is an image contained within. It has a width as a percentage (83%). However, if I am at a resolution where that div element is starting to get a little narrow, the image narrows up as well, but rather than taking up the entire div (as it should), the image just becomes small and appears just a开发者_开发问答t the top of the div. To compensate for this, I want to vertically align my image within the div element. How can I do this?


vertical-align does not work in DIV elements. the only way to do this is to set this property to your div in css :

.divClass
{
   display:table-cell;
   vertical-align:middle;
}

after it, your DIV element will act like TD elemnt of Table.

to align your image in div with specifying percentage for image vertical position look at link bellow (percentage value) :

http://reference.sitepoint.com/css/vertical-align


Give the div position:absolute and the image inside it position:relative with top:50% and margin top equals to negative half the image height. This will center your image vertically.

div{
    border:1px solid red;
    width:400px;
    height:400px;
    position:relative;
}

img{
    position:absolute;
    top:50%;
    margin-top:-64px; /*negative half image height */
}

Check working example at http://jsfiddle.net/qtL4n/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜