0

我们希望页面上的顶部栏与浏览器的宽度一样宽。问题是,它位于容器 div 内。如果你把它从容器中拉出来,我们可以将 div 扩展到 body 宽度,但是当它在容器内时,它只能扩展到容器的宽度。

有没有一种解决方案可以让我们将顶栏扩展到容器 div 之外。

<div id="container">
     <div id="topBar">
         <p>The Paragraph</p>
     </div>
</div>
4

2 回答 2

3

您可以定位#topBar绝对值而不使其相对于其直接父级

html, body {
    height: 2000px;
}

#container {
    width: 50%;
    margin: auto;
    height: 200px;
    background: beige;
}

#topBar {
    position: absolute;
    left: 0;
    background: #ccc;
    width: 100%;
}

演示

于 2012-10-18T17:39:36.323 回答
1

另一种可能性是使用 position:absolute 将其从文档流中删除。但是,您需要知道 topBar 的高度,并且必须通过在其余内容上强制设置上边距以使其低于 topBar 来进行补偿。

例如,您可以这样做:

#topBar {
    position:absolute; /* fixed might also work, here */
    top:0; left:0;
    width:100%;
    height:50px;
}

但你还必须有:

#container {
    margin-top:50px; /* or more */
}

但是,如果您需要制作 #containerposition:absoluteposition:relative.

于 2012-10-18T17:40:32.573 回答