我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
当前回答
就我个人而言,我会把它作为div的背景图像,CSS是这样的:
#demo {
background: url(bg_apple_little.gif) no-repeat center center;
height: 200px;
width: 200px;
}
(假设一个id="demo"的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>
<p style="text-align:center"><img>Image here</img></p>
</div>
通常,我将设置行高为200px。通常是这样的。
这是正确的:
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;
}