CSS - 在浮动 div 中垂直居中图像

Posted

技术标签:

【中文标题】CSS - 在浮动 div 中垂直居中图像【英文标题】:CSS - vertically center an image within a floated div 【发布时间】:2011-04-08 23:49:56 【问题描述】:

我决定在这个问题上认输,需要一些帮助:)。根据标题,尝试垂直对齐包裹在浮动固定高度 div 中心的锚元素中的图像。

为解决方案做了很多谷歌搜索,当 div 不浮动时,我可以得到的壁橱在下面(但它需要浮动)。任何想法将不胜感激!

.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"  /></a>
</div>

【问题讨论】:

【参考方案1】:

好吧,我昨晚遇到了同样的问题(对于类似画廊的东西),并在偶然发现 this page 后设法找到了解决方案。我很高兴地报告这似乎也适用于浮动元素!

诀窍基本上是给外部元素“display: table;”,内部元素(包含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"  /></a>
    </div>
</body>
</html>

对于 IE8,您确实需要处于标准模式。需要一些额外的定位才能让它在 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]-->

【讨论】:

整洁。不知道这是否是最好的方法,但效果很好jsfiddle.net/NgqE2 记得把图片放在其他标签里面。在这种情况下是&lt;a&gt;。否则将无法正常工作。【参考方案2】:

这里有一个跨浏览器 css 解决方案:http://www.vdotmedia.com/blog/vertically-center-content-with-css/

【讨论】:

啊,是的,我遇到了这个。仍然是同样的问题,但当它浮动时,这非常令人沮丧!【参考方案3】:

如果高度是固定的并且您知道图像的大小,则只需手动定位图像。在图像上使用position:absolute;top:25px; 或类似的东西,或为图像添加边距:margin:25px 0;

【讨论】:

不幸的是,有时图像的高度可能不同。不过谢谢!

以上是关于CSS - 在浮动 div 中垂直居中图像的主要内容,如果未能解决你的问题,请参考以下文章

浮动div的内容垂直居中

仅使用css在div中垂直居中图像[重复]

HTML CSS中如何实现DIV中的图片水平垂直居中对齐

在响应式方形 div 中垂直居中图像

如何让div中的行内元素的文字垂直居中

如何让一个浮动元素既水平又垂直居中