我有一个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,因为你已经指定了高度和宽度,添加背景应该不是问题)

让浏览器承担压力。

其他回答

通常,我将设置行高为200px。通常是这样的。

.container {
height: 200px;
width: 200px;
float:left;
position:relative;
}
.children-with-img {
position: absolute;
width:50px;
height:50px;
left:50%;
top:50%;
transform:translate(-50%);
}

垂直对齐是最常被误用的css样式之一。对于不是td或css“display: table-cell”的元素,它不能像你期望的那样工作。

这是一篇关于这个问题的很好的文章。http://phrogz.net/CSS/vertical-align/index.html

实现你想要的目标最常见的方法是:

填充上/下 绝对位置 行高

一个简单而优雅的解决方案,每次都适用于我:

<div>
    <p style="text-align:center"><img>Image here</img></p>
</div>

这是正确的:

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;
}