English 中文(简体)
将一个DIV浮动到另一个DIV
原标题:Float a DIV centered over another DIV

我试图将一个div浮动在另一个div上,但在中心(宽度)。

EDIT:我希望容器div位于顶部div之上并居中。

当前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 solid #CCC;
    width: 920px;
    height:300px;
    position: absolute;
    top:0;
    right:auto;
}

This is what i get: image

最佳回答

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

问题回答

试试这个。它未经测试,但您基本上需要将容器div设置为相对,然后将其中的div设置为绝对。

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;
}

我建议将#top的position属性设置为absolute,并使用一点javascript将left属性设置为#container的left+#container宽度的一半-#top宽度的一半。

即,在包含jQuery(未经测试)之后:

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

在left为零的情况下,就像您给出的示例一样,$(“#container”).css(“left”)术语是不必要的。

EDIT:您还必须确保适当地设置两个div的z-index属性。





相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签