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

怎样才能做到呢?

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


当前回答

通常,我将设置行高为200px。通常是这样的。

其他回答

你可以用下面的代码水平和垂直地居中一个图像(在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的背景图像,CSS是这样的:

#demo {
    background: url(bg_apple_little.gif) no-repeat center center;
    height: 200px;
    width: 200px;
}

(假设一个id="demo"的div,因为你已经指定了高度和宽度,添加背景应该不是问题)

让浏览器承担压力。

https://www.w3.org/Style/Examples/007/center.en.html

IMG.displayed {
  display: block;
  margin-left: auto;
  margin-right: auto 
}

<IMG class="displayed" src="..." alt="...">

在div中

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

简单地设置图像边缘自动如下所示。

img{
 margin:auto;
 width:50%;
 height:auto;
}

检查这些例子