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

怎样才能做到呢?

我能够得到它的中心水平使用文本对齐:中心的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>

其他回答

在div中

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

在CSS中这样做:

img
{

  display:table-cell;
  vertical-align:middle;
  margin:auto;
}

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

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

当然,另一种方法是使用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。