我在JSBin上的问题
我有一个带有文本的div
容器。
<div id="container">
Some text with normal content flow...
<div id="wholescreen">Some 100% text</div>
Some text again, without #wholescreen above the content.
#wholescreen must respect the content flow.
</div>
.CSS
#container {
width: 200px;
margin: auto;
}
在里面,我想要一个 100% 的元素。
#wholescreen {
position: absolute;
left: 0;
width: 100%
}
这行得通。但它在文本之上。所以,我尝试了position: relative
:
#wholescreen {
position: relative;
left: 0;
width: 100%
}
现在还没有结束元素,但也不是 100%。
我做什么?我想要这个结果。
如果#wholescreen
有一个固定的height
,则在元素中直接在其后面添加一个margin-top
:
#wholescreen + * {
margin-top: /* value */;
}
这不会影响其他元素。就像我说的,只有#wholescreen
之后的元素.
» JSBin 示例
如果您可以更改 HTML...
你为什么不试试这个?
<div class="container">Lorem ipsum dolor sit amet.</div>
<div id="wholescreen">100%</div>
<div class="container">Consectetur adipisicing elit.</div>
区别在于一个元素不会是另一个元素的子元素。 :P
» JSBin 示例
给出相对于容器父级的位置并给予 #wholescreen 绝对位置但是,如果您更改任何 #wholescreen 父项的 CSS 属性位置,则可能会破坏此效果
body{
position:relative
}
#wholescreen {
position: absolute;
left: 0;
width: 100%;
top: 50px; // give it a top value
}
如果您希望 #wholescreen 附加到窗口并且在滚动时不移动,请使用
#wholescreen{
position: fixed;
left: 0;
width: 100%;
}
在这里检查小提琴:http://jsfiddle.net/AdVL8/6/
新建编辑
我给了它更好的外观,我意识到你可能不想让元素隐藏文本,所以我认为这就是你想要的效果:
body{
/* remove position: relative; */
}
#wholescreen{
position: relative;
text-align: center;
left: 50%; /* the property that will help us find the center of the screen */
width: 2000px; /* a width wider than any screen */
margin-left: -1000px; /* centers the element (must be 50% of the width) */
}