我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。

怎样才能做到呢?

我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..


当前回答

.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%);
}

其他回答

使用Flexbox:

.outerDiv {
  display: flex;
  flex-direction: column;
  justify-content: center;  /* Centering y-axis */
  align-items :center; /* Centering x-axis */
}

来,试试这个。

.parentdiv { 身高:400 px; 边框:2px实心#cccccc; 背景:# efefef; 位置:相对; } .childcontainer { 位置:绝对的; 左:50%; 上图:50%; } .childdiv { 宽度:150 px; 身高:150 px; 背景:lightgreen; 这个特性:50%; 边框:2px纯绿色; margin-top: -50%; margin-left: -50%; } < div class = " parentdiv”> < div class = " childcontainer”> < div class = " childdiv”> < / div > < / div > < / div >

就我个人而言,我会把它作为div的背景图像,CSS是这样的:

#demo {
    background: url(bg_apple_little.gif) no-repeat center center;
    height: 200px;
    width: 200px;
}

(假设一个id="demo"的div,因为你已经指定了高度和宽度,添加背景应该不是问题)

让浏览器承担压力。

这对我来说很管用:

<body>
  <table id="table-foo">
    <tr><td>
        <img src="foo.png" /> 
    </td></tr>
  </table>
</body>
<style type="text/css">
  html, body {
    height: 100%;
  }
  #table-foo {
    width: 100%;
    height: 100%;
    text-align: center;
    vertical-align: middle;
  }
  #table-foo img {
    display: block;
    margin: 0 auto;
  }
</style>

我发现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;
}