下面是div
<div id="over" style="position:absolute; width:100%; height:100%>
<img src="img.png">
</div>
如何对齐图像,使其位于div的中间和中心?
下面是div
<div id="over" style="position:absolute; width:100%; height:100%>
<img src="img.png">
</div>
如何对齐图像,使其位于div的中间和中心?
当前回答
许多答案建议使用margin:0 auto,但只有当你试图使居中的元素不是浮动在左边或右边时,这才有效,即没有设置CSS属性float。为了做到这一点,将display属性应用到table-cell,然后将左右边距应用到auto,这样你的样式将看起来像style="display:table-cell;margin:0 auto;"
其他回答
水平放置
#over img {
display: block;
margin: 0 auto;
clear:both;
}
另一种方法:
#over img {
display: inline-block;
text-align: center;
}
只需要放置:
#over img {
vertical-align: middle;
}
在我看来,您还希望图像在容器中垂直居中。(我没有看到任何答案提供了这一点)
工作小提琴:
纯CSS解决方案 不中断文档流(没有浮动或绝对定位) 跨浏览器兼容性(甚至包括IE6) 完全响应。
HTML
<div id="over">
<span class="Centerer"></span>
<img class="Centered" src="http://th07.deviantart.net/fs71/200H/f/2013/236/d/b/bw_avlonas_a5_beach_isles_wallpaper_image_by_lemnosexplorer-d6jh3i7.jpg" />
</div>
CSS
*
{
padding: 0;
margin: 0;
}
#over
{
position:absolute;
width:100%;
height:100%;
text-align: center; /*handles the horizontal centering*/
}
/*handles the vertical centering*/
.Centerer
{
display: inline-block;
height: 100%;
vertical-align: middle;
}
.Centered
{
display: inline-block;
vertical-align: middle;
}
注意:此解决方案适用于在任何元素中对齐任何元素。 对于IE7,当在块元素上应用.居中类时,你将不得不使用另一个技巧来让内联块工作。(这是因为IE6/IE7不能很好地使用内联块对块元素)
<div style="display:table-cell; vertical-align:middle; text-align:center">
<img src="img.png">
</div>
这也可以使用Flexbox布局完成:
静态的大小 .parent { 显示:flex; 身高:300 px;/*或者*/ background - color: # 000; } .child { 宽度:100 px;/*或者*/ 身高:100 px;/*或者*/ 保证金:汽车;/ *魔法!* / } < div class = "父" > <img class="child" src="https://i.vimeocdn.com/portrait/58832_300x300"/> < / div >
动态规模 Html, body { 宽度:100%; 高度:100%; 显示:flex; background - color: # 999; } * { 保证金:0; 填充:0; } .parent { 保证金:汽车; background - color: # 000; 显示:flex; 高度:80%; 宽度:80%; } .child { 保证金:汽车;/ *魔法!* / max-width: 100%; max-height: 100%; } < div class = "父" > <img class="child" src="https://i.vimeocdn.com/portrait/58832_300x300"/> < / div >
我在这篇文章中找到了一个例子,它很好地解释了如何使用布局。
这将是一种更简单的方法
#over > img{
display: block;
margin:0 auto;
}