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

怎样才能做到呢?

我能够得到它的中心水平使用文本对齐:中心的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和图像的大小,你可以使用绝对定位。

这是另一种将所有内容居中的方法。

工作小提琴

HTML:(一如既往的简单)

<div class="Container">
    <div class="Content"> /*this can be an img, span, or everything else*/
        I'm the Content
    </div>
</div>

CSS:

.Container
{
    text-align: center;
}

    .Container:before
    {
        content: '';
        height: 100%;
        display: inline-block;
        vertical-align: middle;
    }

.Content
{
    display: inline-block;
    vertical-align: middle;
}

好处

容器和内容高度未知。

居中没有特定的负边距,没有设置行高(所以它适用于多行文本),没有脚本,也适用于CSS过渡。

在div中

style="text-align:center; line-height:200px"

这对我很管用。将此添加到image css:

img
{
   display: block;
   margin: auto;
}

我喜欢跳老式马车!

以下是这个答案在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。