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

怎样才能做到呢?

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


当前回答

另一种方法(此处未提及)是使用Flexbox。

只需在container div上设置以下规则:

display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */

小提琴

div { 宽度:200 px; 身高:200 px; 边框:1px纯绿色; 显示:flex; justify-content:中心; /*对齐水平*/ 对齐项目:中心; /*垂直对齐*/ } < div > < img src = " http://lorempixel.com/50/50/food " alt = " / > < / div >

要了解Flexbox的一些特性并获得最大限度的浏览器支持的语法,最好从flexyboxes开始

此外,现在的浏览器支持也相当不错:caniuse

对于显示:flex和align-items的跨浏览器兼容性,您可以使用以下命令:

display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

其他回答

谢谢大家提供的线索。

我用了这个方法

div.image-thumbnail
{
    width: 85px;
    height: 85px;
    line-height: 85px;
    display: inline-block;
    text-align: center;
}
div.image-thumbnail img
{
    vertical-align: middle;
}

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

你可以用下面的代码水平和垂直地居中一个图像(在IE/FF中工作)。 它会将图像的上边缘放置在浏览器高度的50%,而margin-top(向上拉图像高度的一半)将完美地居中。

<style type="text/css">
    #middle {position: absolute; top: 50%;} /* for explorer only*/
    #middle[id] {vertical-align: middle; width: 100%;}
         #inner {position: relative; top: -50%} /* for explorer only */
</style>


<body style="background-color:#eeeeee">
    <div id="middle">
        <div id="inner" align="center" style="margin-top:...px"> /* the number will be half the height of your image, so for example if the height is 500px then you will put 250px for the margin-top */
            <img src="..." height="..." width="..." />
        </div>
    </div>
</body>

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

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

在div中

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