【发布时间】:2011-11-12 06:49:33
【问题描述】:
如何在包含div 的内部对齐图像?
示例
在我的示例中,我需要将<div> 中的<img> 与class ="frame 垂直居中:
<div class="frame" style="height: 25px;">
<img src="http://jsfiddle.net/img/logo.png" />
</div>
.frame 的高度是固定的,图像的高度是未知的。如果这是唯一的解决方案,我可以在 .frame 中添加新元素。我正在尝试在 Internet Explorer 7 及更高版本、WebKit、Gecko 上执行此操作。
请参阅 jsfiddle here。
.frame {
height: 25px; /* Equals maximum image height */
line-height: 25px;
width: 160px;
border: 1px solid red;
text-align: center;
margin: 1em 0;
}
img {
background: #3A6F9A;
vertical-align: middle;
max-height: 25px;
max-width: 160px;
}
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=250 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=25 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=23 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=21 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=19 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=17 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=15 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=13 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=11 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=9 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=7 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=5 />
</div>
<div class=frame>
<img src="http://jsfiddle.net/img/logo.png" height=3 />
</div>
【问题讨论】:
-
您好,抱歉,但我不同意在这里使用助手作为最有价值的解决方案。但这不是唯一的方法。其他浏览器同样支持。我在 stackoverflow.com/a/43308414/7733724 和 W3C.org 上提供了有关信息的解决方案。你可以检查一下。干杯
-
阅读有关 W3C 的 Centering Things 文章会很有用:w3.org/Style/Examples/007/center.en.html
-
完美指南 align css-tricks.com/centering-css-complete-guide
-
我认为关键是 .frame 中的行高来完成这项工作
标签: css image vertical-alignment