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

怎样才能做到呢?

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


当前回答

使用Flexbox:

.outerDiv {
  display: flex;
  flex-direction: column;
  justify-content: center;  /* Centering y-axis */
  align-items :center; /* Centering x-axis */
}

其他回答

这有点晚了,但这里有一个解决方案,我用垂直对齐元素在一个父div。

当您知道容器div的大小,但不知道包含的图像的大小时,这是有用的。(这是在使用灯箱或图像旋转木马时经常出现的情况)。

以下是你应该尝试的发型:

 container div
 {
   display:table-cell;
   vertical-align:middle;

   height:200px;
   width:200px;
 }

 img
 {
   /*Apply any styling here*/        
 }

我有一个图片库,我不知道准确的高度或宽度的图像之前,我只知道他们是小于div,他们将被包含。

通过在容器上组合行高设置并在图像元素上使用vertical-align:middle,我最终使用以下HTML标记和以下CSS使其在FF 3.5、Safari 4.0和IE7.0上工作。

HTML标记

<div id="gallery">
    <div class="painting">
        <a href="Painting/Details/2">
            <img src="/Content/Images/Paintings/Thumbnail/painting_00002.jpg" />
        </a>
    </div>
    <div class="painting">
        ...
    </div>
    ...
 </div>

CSS

div.painting
{
    float:left;

    height:138px; /* fixed dimensions */
    width: 138px;

    border: solid 1px white;
    background-color:#F5F5F5;


    line-height:138px;    
    text-align:center;

}

    div.painting a img
    {
        border:none;
        vertical-align:middle;

    }

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

我喜欢跳老式马车!

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

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

工作小提琴

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过渡。