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

怎样才能做到呢?

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


当前回答

来,试试这个。

.parentdiv { 身高:400 px; 边框:2px实心#cccccc; 背景:# efefef; 位置:相对; } .childcontainer { 位置:绝对的; 左:50%; 上图:50%; } .childdiv { 宽度:150 px; 身高:150 px; 背景:lightgreen; 这个特性:50%; 边框:2px纯绿色; margin-top: -50%; margin-left: -50%; } < div class = " parentdiv”> < div class = " childcontainer”> < div class = " childdiv”> < / div > < / div > < / 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过渡。

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

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

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

填充上/下 绝对位置 行高

我一直在尝试用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>

这是一种老式的解决方案,但浏览器市场份额已经足够大了,如果你不担心IE7的性能下降,你可能不需要IE黑客的部分。当你知道外部容器的尺寸,但可能知道也可能不知道内部图像的尺寸时,这种方法是有效的。

.parent {
    display: table;
    height: 200px; /* can be percentages, too, like 100% */
    width: 200px; /* can be percentages, too, like 100% */
}

.child {
    display: table-cell;
    vertical-align: middle;
    margin: 0 auto;
}
 <div class="parent">
     <div class="child">
         <img src="foo.png" alt="bar" />
     </div>
 </div>

我有一个图片库,我不知道准确的高度或宽度的图像之前,我只知道他们是小于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;

    }