【发布时间】:2010-12-09 02:21:27
【问题描述】:
我试图在已知大小的 div 中将未知大小的图像居中,以便图像在 div 中垂直和水平居中,并且图像的纵横比不会失真。
这是example
这段代码几乎可以完成这项工作,但两个图像看起来都略微向下移动了......可能有几个像素。为什么?
HTML;
<body>
<div class="container" id="c1">
<img src="test.jpg"/>
</div>
<div class="container" id="c2">
<img src="test.jpg"/>
</div>
</body>
CSS;
.container {
text-align: center; /* Center the image horizontally */
margin: 1em; /* Just for looks */
background: red; /* Just for looks */
}
.container img {
vertical-align: middle; /* See note below */
max-height: 100%; /* Limit the image size to fit the container */
max-width: 100%; /* Limit the image size to fit the container */
}
#c1 {
width: 8em;
height: 4em; /* See note below */
line-height: 4em; /* See note below */
}
#c2 {
width: 5em;
height: 7em; /* See note below */
line-height: 7em; /* See note below */
}
注意:通过使容器的 line-height 与容器的高度相同,并将 {vertical-align: middle;} 应用于图像,图像在容器内垂直居中。这应该使容器内的图像垂直居中,并且几乎可以正常工作,只是图像总是太低两个像素。
我试过做 * {margin:0; padding:0} 和几个 reset.css 文件,但图像似乎仍然向下移动了一点。
所以我的问题实际上是两个问题;
- 未知大小的图像如何在已知大小的 div 中居中?
- 为什么img和div的边缘之间有一个小间隙?
问候,CSS 新手。
【问题讨论】:
-
是我还是 HTML 不全?
-
@ClarkeyBoy 修复了这个问题,没有正确缩进。