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

怎样才能做到呢?

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


当前回答

我喜欢跳老式马车!

以下是这个答案在2015年的更新。我开始使用CSS3 transform来做我的定位工作。这允许你不需要做任何额外的HTML,你不需要做数学(找到半宽的东西),你可以在任何元素上使用它!

这里有一个例子(最后是小提琴)。HTML:

<div class="bigDiv">
    <div class="smallDiv">
    </div>
</div>

附带CSS:

.bigDiv {
    width:200px;
    height:200px;
    background-color:#efefef;
    position:relative;
}
.smallDiv {
    width:50px;
    height:50px;
    background-color:#cc0000;
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%, -50%);
}

我最近经常做的就是给我想居中的东西一个类然后每次都重用这个类。例如:

<div class="bigDiv">
    <div class="smallDiv centerThis">
    </div>
</div>

css

.bigDiv {
    width:200px;
    height:200px;
    background-color:#efefef;
    position:relative;
}
.smallDiv {
    width:50px;
    height:50px;
    background-color:#cc0000;
}
.centerThis {
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%, -50%);
}

通过这种方式,我将始终能够将容器中的内容居中。你只需要确保你想居中的东西是在一个定义了位置的容器中。

这是小提琴

BTW:这也适用于在较小的divs中居中更大的divs。

其他回答

这是正确的:

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

你可以用下面的代码水平和垂直地居中一个图像(在IE/FF中工作)。 它会将图像的上边缘放置在浏览器高度的50%,而margin-top(向上拉图像高度的一半)将完美地居中。

<style type="text/css">
    #middle {position: absolute; top: 50%;} /* for explorer only*/
    #middle[id] {vertical-align: middle; width: 100%;}
         #inner {position: relative; top: -50%} /* for explorer only */
</style>


<body style="background-color:#eeeeee">
    <div id="middle">
        <div id="inner" align="center" style="margin-top:...px"> /* the number will be half the height of your image, so for example if the height is 500px then you will put 250px for the margin-top */
            <img src="..." height="..." width="..." />
        </div>
    </div>
</body>

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

当然,另一种方法是使用valign创建一个表。不管你是否知道div的高度,这都可以工作。

<div>
   <table width="100%" height="100%" align="center" valign="center">
   <tr><td>
      <img src="foo.jpg" alt="foo" />
   </td></tr>
   </table>
</div>

但只要可能,您应该始终坚持只使用CSS。

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