我们希望页面上的顶栏与浏览器的宽度一样宽。问题是,它在容器div中。如果你将它从容器中拉出来,我们可以将div扩展到主体宽度,但当它在容器内部时,它只能扩展到容器的宽度。
是否有解决方案可以将topbar扩展到容器div之外。
<div id="container">
<div id="topBar">
<p>The Paragraph</p>
</div>
</div>
答案 0 :(得分:3)
您可以将#topBar
绝对定位,而不必将其置于其“直接父级”
html, body {
height: 2000px;
}
#container {
width: 50%;
margin: auto;
height: 200px;
background: beige;
}
#topBar {
position: absolute;
left: 0;
background: #ccc;
width: 100%;
}
答案 1 :(得分:1)
另一种可能性是将其从位置:绝对的文档流中删除。但是,您需要知道topBar的高度,并且必须通过强制保留其余内容的上边距来使其保持在topBar之下。
例如,你可以这样做:
#topBar {
position:absolute; /* fixed might also work, here */
top:0; left:0;
width:100%;
height:50px;
}
但你也必须:
#container {
margin-top:50px; /* or more */
}
但是,如果您需要制作#container position:absolute
或position:relative
,这将会中断。