如何使用CSS在HTML中的div元素内垂直居中放置图像? [英] How to vertically center an image inside of a div element in HTML using CSS?
问题描述
我有这样的标记:
<div>
<img />
</div>
div高于img:
div {
height: 100px;
}
img {
height: dynamic-value-smaller-than-100px;
}
我需要将图像放置在div的中间(在其上下具有相同的空白).
I need the image to be in the middle of the div (have same amout of white space above and below it).
我尝试了此操作,但它不起作用:
I tried this and it does not work:
div {
vertical-align: middle;
}
推荐答案
如果您的图像纯粹是装饰性的,那么将其用作背景图像可能是一种更具语义的解决方案.然后,您可以指定背景的位置
if your image is purely decorative, then it might be a more semantic solution to use it as a background-image. You can then specify the position of the background
background-position: center center;
如果它不是装饰性的并且构成有价值的信息,则img标签是合理的.在这种情况下,您需要为包含div的样式设置以下属性:
If it is not decorative and constitutes valuable information then the img tag is justified. What you need to do in such case is style the containing div with the following properties:
div{
display: table-cell; vertical-align: middle
}
在此处详细了解此技术.据说无法在IE6/7上运行(在IE8上运行).
Read more about this technique here. Reported to not work on IE6/7 (works on IE8).
这篇关于如何使用CSS在HTML中的div元素内垂直居中放置图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!