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

怎样才能做到呢?

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


当前回答

我们可以使用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 >

其他回答

你可以用下面的代码水平和垂直地居中一个图像(在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>

另一种方法(此处未提及)是使用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;

这是正确的:

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

当然,另一种方法是使用valign创建一个表。不管你是否知道div的高度,这都可以工作。

<div>
   <table width="100%" height="100%" align="center" valign="center">
   <tr><td>
      <img src="foo.jpg" alt="foo" />
   </td></tr>
   </table>
</div>

但只要可能,您应该始终坚持只使用CSS。

这是一种老式的解决方案,但浏览器市场份额已经足够大了,如果你不担心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>