CSS - 垂直居中浮动div中的图像 [英] CSS - vertically center an image within a floated div
问题描述
我决定把毛巾放在这个问题上,需要一些帮助:)。根据标题试图垂直对齐包含在浮动固定高度div中心的锚元素的图像。
I've decided to throw in the towel on this problem and need some help :). As per title trying to vertically align an image wrapped in an anchor element in the center of a floated fixed height div.
完成了大量的搜索解决方案,我可以得到的衣柜是下面当div不浮动(但它需要)。任何想法都将非常感谢!
Done a lot of googling for solutions and the closet I can get is below when the div is not floated (however it needs to be). Any ideas would be greatfully appreciated!
.class_name {
/*float: left*/
width:153px;
height:153px;
margin:3px;
padding:4px;
border:1px solid #dedede;
text-align: center;
vertical-align: middle;
background-color: #000;
display: table-cell;
}
<div class="class_name">
<a href=""><img src="image.jpg" alt="" /></a>
</div>
推荐答案
对于画廊样的事情),并设法找到一个解决方案后,绊倒到此页。我很高兴地报告这似乎也适用于浮动的元素!
Well, I bumped into the same issue last night (for a gallery-like type of thing), and managed to find a solution after stumbling onto this page. I'm happy to report this also seems to work for floated elements!
诀窍基本上是给外部元素display:table;, (包含img)display:table-cell;。
The trick is basically to give the outer element "display: table;", and the inner element (containing the img) "display: table-cell;".
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html><head>
<style type="text/css">
.class_name {
display: table;
float: left;
overflow: hidden;
width: 153px;
height: 153px;
}
.class_name a {
display: table-cell;
vertical-align: middle;
text-align: center;
}
</style>
</head>
<body>
<div class="class_name">
<a href=""><img src="image.jpg" alt="" /></a>
</div>
</body>
</html>
对于IE8,您需要处于标准模式。需要一些额外的定位以使它在IE7中工作:
For IE8, you do need to be in standards mode. Some additional positioning is needed to get it to work in IE7:
<!--[if lte IE 7]><style type="text/css">
.class_name {
position: relative;
}
.class_name a {
position: absolute;
top: 50%;
}
.class_name img {
position: relative;
top: -50%;
width: 100%;
}
</style><![endif]-->
这篇关于CSS - 垂直居中浮动div中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!