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

怎样才能做到呢?

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


当前回答

你可以设置图像的位置是对齐中心水平

#imageId {
   display: block;
   margin-left: auto;
   margin-right:auto;
}

其他回答

我将设置你的大div位置:相对;然后为你的形象这样做:

img.classname{
   position:absolute;
   top:50%;
   left:50%;
   margin-top:-25px;
   margin-left:-25px;
}

这只是因为你知道图像和包含的div的尺寸。这也可以让你在包含的div中有其他项目…而使用行高之类的解决方案则不会。

编辑:注意…你的页边距是图像大小的负一半。

div { position: absolute; border: 3px solid green; width: 200px; height: 200px; } img { position: relative; border: 3px solid red; width: 50px; height: 50px; } .center { top: 50%; left: 50%; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); /* IE 9 */ -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */ } <div class="center"> <img class="center" src="http://placeholders.org/250/000/fff" /> </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;
}

我们可以使用flex轻松实现这一点。不需要背景图片。

<!DOCTYPE html > < html > < >头 <时尚> # image-wrapper { 宽度:500 px; 身高:500 px; 边框:1px实体#333; 显示:flex; justify-content:中心; 对齐项目:中心; } > < /风格 > < /头 身体< > < div id = " image-wrapper " > <img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png"> < / div > < /身体> < / html >