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

怎样才能做到呢?

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


当前回答

https://www.w3.org/Style/Examples/007/center.en.html

IMG.displayed {
  display: block;
  margin-left: auto;
  margin-right: auto 
}

<IMG class="displayed" src="..." alt="...">

其他回答

将图像垂直和水平居中的最好方法是使用两个容器,并应用以下属性:

外面的容器

应有显示:表;

内容器

应该有display: table-cell; 应该有垂直对齐:中间; 应该有text-align: center;

一个演示

.outer-container { display: table; width: 80%; /* can be any width */ height: 120px; /* can be any height */ background: #ccc; } .inner-container { display: table-cell; vertical-align: middle; text-align: center; } .inner-container img { background: #fff; padding : 10px; border : 1px solid #000; } <div class="outer-container"> <div class="inner-container"> <img src="http://s.gravatar.com/avatar/bf4cc94221382810233575862875e687?r=x&s=50" /> </div> </div>

使用定位。下面的方法对我很有效:

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

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