我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
当前回答
你可以用下面的代码水平和垂直地居中一个图像(在IE/FF中工作)。 它会将图像的上边缘放置在浏览器高度的50%,而margin-top(向上拉图像高度的一半)将完美地居中。
<style type="text/css">
#middle {position: absolute; top: 50%;} /* for explorer only*/
#middle[id] {vertical-align: middle; width: 100%;}
#inner {position: relative; top: -50%} /* for explorer only */
</style>
<body style="background-color:#eeeeee">
<div id="middle">
<div id="inner" align="center" style="margin-top:...px"> /* the number will be half the height of your image, so for example if the height is 500px then you will put 250px for the margin-top */
<img src="..." height="..." width="..." />
</div>
</div>
</body>
其他回答
如果你知道父div和图像的大小,你可以使用绝对定位。
垂直对齐是最常被误用的css样式之一。对于不是td或css“display: table-cell”的元素,它不能像你期望的那样工作。
这是一篇关于这个问题的很好的文章。http://phrogz.net/CSS/vertical-align/index.html
实现你想要的目标最常见的方法是:
填充上/下 绝对位置 行高
适用于旧浏览器(IE >= 8)
绝对位置与自动边距相结合可以使元素水平和垂直居中。元素位置可以基于使用相对定位的父元素位置。查看结果
img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
谢谢大家提供的线索。
我用了这个方法
div.image-thumbnail
{
width: 85px;
height: 85px;
line-height: 85px;
display: inline-block;
text-align: center;
}
div.image-thumbnail img
{
vertical-align: middle;
}
我发现Valamas和Lepu上面的答案是最直接的答案,处理未知大小的图像,或已知大小的图像,你宁愿不硬编码到你的CSS中。我只是做了一些小调整:删除不相关的样式,大小为200px以匹配问题,并添加max-height/max-width来处理可能过大的图像。
div.image-thumbnail
{
width: 200px;
height: 200px;
line-height: 200px;
text-align: center;
}
div.image-thumbnail img
{
vertical-align: middle;
max-height: 200px;
max-width: 200px;
}