我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
当前回答
这对我很管用。将此添加到image css:
img
{
display: block;
margin: auto;
}
其他回答
这有点晚了,但这里有一个解决方案,我用垂直对齐元素在一个父div。
当您知道容器div的大小,但不知道包含的图像的大小时,这是有用的。(这是在使用灯箱或图像旋转木马时经常出现的情况)。
以下是你应该尝试的发型:
container div
{
display:table-cell;
vertical-align:middle;
height:200px;
width:200px;
}
img
{
/*Apply any styling here*/
}
使用定位。下面的方法对我很有效:
div{
display:block;
overflow:hidden;
width: 200px;
height: 200px;
position: relative;
}
div img{
width: 50px;
height: 50px;
top: 50%;
left: 50%;
bottom: 50%;
right: 50%;
position: absolute;
}
通常,我将设置行高为200px。通常是这样的。
简单地设置图像边缘自动如下所示。
img{
margin:auto;
width:50%;
height:auto;
}
检查这些例子
这是正确的:
display: block;
margin-left: auto;
margin-right: auto
否则,如果上面只给你水平居中,试试这个:
.outerContainer {
position: relative;
}
.innerContainer {
width: 50px; //your image/element width here
height: 50px; //your image/element height here
overflow: auto;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}