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

怎样才能做到呢?

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


当前回答

垂直对齐是最常被误用的css样式之一。对于不是td或css“display: table-cell”的元素,它不能像你期望的那样工作。

这是一篇关于这个问题的很好的文章。http://phrogz.net/CSS/vertical-align/index.html

实现你想要的目标最常见的方法是:

填充上/下 绝对位置 行高

其他回答

这是正确的:

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

我有这个问题在HTML5中使用CSS3和我的图像在DIV中居中…哦,是的,我不能忘记我必须增加高度来显示图像…有一段时间我不知道它在哪里,直到我做了这个。我不认为位置和显示是必要的。

background-image: url('../Images/01.png');    
background-repeat:no-repeat;
background-position:center;
position:relative;
display:block;
height:60px;

使用Flexbox:

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

easy

img {
    transform: translate(50%,50%);
}

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

工作小提琴

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