垂直对齐div中的图像 [英] Vertical align an image in a div

查看:74
本文介绍了垂直对齐div中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过很多关于一个简单任务的问题:如何在div中垂直对齐图片。

I've seen multiple questions about a pretty simple task: how to vertically align an image in a div.

我的代码( http://jsfiddle.net/3cYtX/1/ )很简单:

.container {
    width:200px;
    height:200px;
    background-color: green;    
}
img.middle {    
    vertical-align:middle;
}
<div class="container">
    <img class="middle" src="test.gif" width="80" height="40" />
</div>

我的代码对齐图像。如何解决?

My code does not align the image. How to fix it?

推荐答案

您可以使div像表格单元格一样:

You can make the div behave like a table cell:

演示: http://jsfiddle.net/abhitalks/ 3cYtX / 5 /

.container {
    display: table-cell; /* make it behave like a table cell */
    vertical-align: middle; /* make it align contents vertically */
    text-align: center; /* make it align contents horizontally */
}

注意:设置为 table-cell 的注释,元素应该理想地是具有显示 table table-row 。例如 http://jsfiddle.net/abhitalks/3cYtX/8/

Note: As James pointed out in the comments, elements set to table-cell should ideally be content of elements with display table or table-row. e.g. http://jsfiddle.net/abhitalks/3cYtX/8/

这篇关于垂直对齐div中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆