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

怎样才能做到呢?

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


当前回答

在CSS中这样做:

img
{

  display:table-cell;
  vertical-align:middle;
  margin:auto;
}

其他回答

来,试试这个。

.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 >

这对我来说很管用:

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

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

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

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

让浏览器承担压力。

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

这是一种老式的解决方案,但浏览器市场份额已经足够大了,如果你不担心IE7的性能下降,你可能不需要IE黑客的部分。当你知道外部容器的尺寸,但可能知道也可能不知道内部图像的尺寸时,这种方法是有效的。

.parent {
    display: table;
    height: 200px; /* can be percentages, too, like 100% */
    width: 200px; /* can be percentages, too, like 100% */
}

.child {
    display: table-cell;
    vertical-align: middle;
    margin: 0 auto;
}
 <div class="parent">
     <div class="child">
         <img src="foo.png" alt="bar" />
     </div>
 </div>