有几种方法可以做到这一点 - 纯CSS或基于JS的方法。
更新后的答案
更新:随着CSS变换支持的出现,使用纯CSS定位元素的解决方案相当优雅。使用给定的标记:
<div class="container">
<img src="..." alt="..." title="..." />
</div>
对于您的CSS:
.container {
position: relative;
}
.container img {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
更新后的JSFiddle
旧回答
对于CSS,您可以在<img>
元素的容器中构建一个幽灵元素。Chris Coyier在这个技术方案上写了一篇很好的文章。假设你的HTML代码看起来像这样:
<div class="container">
<img src="..." alt="..." title="..." />
</div>
那么你的CSS将会是:
.container {
font-size: 0;
text-align: center;
}
.container:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
}
.container > img {
display: inline-block;
vertical-align: middle;
}
这个功能性的CSS修复方法可以在这个代码片段中查看:http://jsfiddle.net/teddyrised/yawTb/8/
或者,您也可以使用基于JS的方法:
$(document).ready(function() {
$(window).resize(function() {
$(".container > img").each(function() {
var cHeight = $(this).parent(".container").height(),
cWidth = $(this).parent(".container").width(),
iHeight = $(this).height(),
iWidth = $(this).width();
$(this).css({
top: 0.5*(cHeight - iHeight),
left: 0.5*(cWidth - iWidth)
});
});
}).resize();
});
但是你需要使用以下CSS:
.container {
position: relative;
}
.container img {
position: absolute;
z-index: 100;
}
[编辑]: 对于基于JS的方法,您需要将图像元素的位置绝对定位,您必须明确指定.container
元素的尺寸,或者在其中添加一些内容(但这有点违背了初衷,因为图像将位于内容之上)。这是因为图像元素已经被从文档流中移除,因此其尺寸不会影响父容器的大小。
JS版本的工作示例在这里 - http://jsfiddle.net/teddyrised/yawTb/7/
position:relative
,图像使用position:absolute
。然后添加固定高度和top:50%; margin-top:-height/2
。最后根据不同的媒体查询进行调整。 - elclanrs