开发者

Float a DIV centered over another DIV

I'm trying to float a div over another one but in the center (width).

EDIT: I want the container div to be over the top div and centered.

Current CSS:

body {
    background-color: #FFF;
    margin: auto;
}

#top {
    background-color: #F2F2F2;
    border-bottom: 1px solid #CCC;
    height: 150px;
    position: relative;
}

#container {
    background-color: #FFF;
    border: 1px soli开发者_StackOverflow中文版d #CCC;
    width: 920px;
    height:300px;
    position: absolute;
    top:0;
    right:auto;
}

This is what i get:

Float a DIV centered over another DIV


set left:50% and margin-left:-460px (half the width of the div)


Try this. It's untested but you basically need to set the container div to relative and then the div inside that to absolute.

body {
        background-color: #FFF;
        margin: auto;
    }

#top {
    background-color: #F2F2F2;
    border-bottom: 1px solid #CCC;
    top: 50%;
    left: 50%;
    position: absolute;
}

#container {
    background-color: #FFF;
    border: 1px solid #CCC;
    width: 920px;
    height:300px;
    position: relative;
    right:auto;
}


I would suggest setting #top's position attribute to absolute and using a little javascript to set the left attribute to #container's left + half of #container's width - half of #top's width.

i.e, after including jQuery (untested):

$(document).ready(function(){
    var topLeft = $("#container").css("left") + ($("#container").css("width")/2) - ($("#top").css("width")/2);
    $("#top").css("left", topLeft);
});

In the case that left is zero, like the example you gave, that $("#container").css("left") term is unnecessary.

EDIT: You'll also have to be sure to set the z-index attributes of the two divs appropriately.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜