我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
当前回答
当然,另一种方法是使用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。
其他回答
将图像垂直和水平居中的最好方法是使用两个容器,并应用以下属性:
外面的容器
应有显示:表;
内容器
应该有display: table-cell; 应该有垂直对齐:中间; 应该有text-align: center;
一个演示
.outer-container { display: table; width: 80%; /* can be any width */ height: 120px; /* can be any height */ background: #ccc; } .inner-container { display: table-cell; vertical-align: middle; text-align: center; } .inner-container img { background: #fff; padding : 10px; border : 1px solid #000; } <div class="outer-container"> <div class="inner-container"> <img src="http://s.gravatar.com/avatar/bf4cc94221382810233575862875e687?r=x&s=50" /> </div> </div>
当然,另一种方法是使用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。
你可以使用以下属性轻松做到这一点:
#内容{ 显示:flex; 对齐项目:中心; 宽度:200 px; 身高:200 px; 边框:1px纯红色; } # myImage { 显示:块; 宽度:50 px; 高度:50 px; 保证金:汽车; 边框:1px纯黄色; } < div id = "内容" > <img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png"> < / div >
引用:W3
我有一个图片库,我不知道准确的高度或宽度的图像之前,我只知道他们是小于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;
}
你可以用下面的代码水平和垂直地居中一个图像(在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>