在浮动div中垂直对齐img

时间:2012-02-14 04:41:37

标签: javascript html css

有5个浮动的div使用Javascript将高度拉伸到document高度的100%。其中所有5个都包含img元素。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link type="text/css" rel="stylesheet" href="style.css"/>
</head>
<body>
    <div id="wrapper">
        <div id="static"><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
        <div><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
        <div><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
        <div><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
        <div class="clear"><img src="http://www.rs.dhamma.org/wheel.gif"/></div>
    </div>
</body>
</html>​

Javascript:

//sets columns height to 100%;
function colsHeight(){
        var docHeight = $(document).height();
        $("#wrapper div").height(docHeight);
};

$(document).ready(function(){
    colsHeight();
    });

和CSS:

*{
    margin: 0;
    padding: 0;    
    }

#wrapper{
 width: 1000px;
 margin: 0 auto;    
    }

    #wrapper div{    
        padding: 0 20px;
        background-color: #9F81F7;        
        float: left;
        border-right: 1px solid black;
    }
    #wrapper img{

    }

div.clear:after{
    content: " ";
    clear: both;
    }

我已尝试设置父级div display: tableimg display: table-cell, vertical-align: middle,但没有运气。定义margin-top: 50%除了预期之外什么都没有。

JSFIDDLE HERE!!!

任何帮助表示赞赏。
谢谢!

4 个答案:

答案 0 :(得分:2)

您可以绝对定位它们,然后设置top: 50%margin-top: -63px。当然,这只有在你知道图像的高度时才有效(126px在你的情况下)。如果图像大小是动态的,最简单但令人讨厌的方法是在加载后使用js在图像上设置margin-top。

无论如何,静态方法可以在这里看到:http://jsfiddle.net/3gqcS/2/

答案 1 :(得分:2)

因为你使用javascript和jQuery(不能没有他)你可以做....

检查一下:http://jsfiddle.net/828pW/

这是代码:

function verticalAlignImage(img)
{
    if(img.height)
    {

        $(img).css({
            position:'absolute',
            top: ($(img).parent().height() - img.height)/2
        }).parent().css('position', 'relative');

    }
    else 
    {
        setTimeout(function(){

            verticalAlignImage(img);
        }, 100);
    }
}

答案 2 :(得分:2)

这感觉有点脏,但你可以将div的行高设置为div高度+图像高度然后溢出:隐藏

<div id="static" style="height: 481px; line-height: 607px; overflow: hidden;">

答案 3 :(得分:1)

尝试设置列:

    position:relative;
    width:<width>;/* width must be set */

和图像为:

    position:absolute;
    top:0;
    bottom:0;
    margin:auto 0;

那应该完美地居中,然后你需要设置列宽,因为绝对定位的图像根本不占用空间。

此外,不要使用java脚本,只需添加:

    html, body, #wrapper, #wrapper div{height:100%;}

代替。

了解到:http://www.tutwow.com/htmlcss/quick-tip-css-100-height/