我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
当前回答
通常,我将设置行高为200px。通常是这样的。
其他回答
在CSS中这样做:
img
{
display:table-cell;
vertical-align:middle;
margin:auto;
}
适用于旧浏览器(IE >= 8)
绝对位置与自动边距相结合可以使元素水平和垂直居中。元素位置可以基于使用相对定位的父元素位置。查看结果
img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
这有点晚了,但这里有一个解决方案,我用垂直对齐元素在一个父div。
当您知道容器div的大小,但不知道包含的图像的大小时,这是有用的。(这是在使用灯箱或图像旋转木马时经常出现的情况)。
以下是你应该尝试的发型:
container div
{
display:table-cell;
vertical-align:middle;
height:200px;
width:200px;
}
img
{
/*Apply any styling here*/
}
你可以用下面的代码水平和垂直地居中一个图像(在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>
这对我很管用。将此添加到image css:
img
{
display: block;
margin: auto;
}