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

怎样才能做到呢?

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


当前回答

将图像垂直和水平居中的最好方法是使用两个容器,并应用以下属性:

外面的容器

应有显示:表;

内容器

应该有display: table-cell; 应该有垂直对齐:中间; 应该有text-align: center;

一个演示

.outer-container { display: table; width: 80%; /* can be any width */ height: 120px; /* can be any height */ background: #ccc; } .inner-container { display: table-cell; vertical-align: middle; text-align: center; } .inner-container img { background: #fff; padding : 10px; border : 1px solid #000; } <div class="outer-container"> <div class="inner-container"> <img src="http://s.gravatar.com/avatar/bf4cc94221382810233575862875e687?r=x&s=50" /> </div> </div>

其他回答

我一直在尝试用hmtl和css让图像在圆形内垂直和水平居中。

在结合了这篇文章中的几个观点后,我得出了以下结论:jsFiddle

下面是三列布局中的另一个示例:jsFiddle

CSS:

#circle {
width: 100px;
height: 100px;
background: #A7A9AB;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
margin: 0 auto;
position: relative;
}

.images {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}

HTML:

<div id="circle">
<img class="images" src="https://png.icons8.com/facebook-like-filled/ios7/50" />
</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过渡。

我们可以使用flex轻松实现这一点。不需要背景图片。

<!DOCTYPE html > < html > < >头 <时尚> # image-wrapper { 宽度:500 px; 身高:500 px; 边框:1px实体#333; 显示:flex; justify-content:中心; 对齐项目:中心; } > < /风格 > < /头 身体< > < div id = " image-wrapper " > <img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png"> < / div > < /身体> < / html >

一个简单而优雅的解决方案,每次都适用于我:

<div>
    <p style="text-align:center"><img>Image here</img></p>
</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;
}