[英]Possible to have 100% screen width inside limited div with relative position?
I wonder if it's possible to have a div stretch to 100vw
, while being inside a relative
parent div with limited width.我想知道是否可以将 div拉伸到100vw
,同时位于宽度有限的relative
父 div 内。 And in the process also not losing it's height inside the document, as it would when setting position to absolute.并且在此过程中也不会丢失它在文档内的高度,就像将位置设置为绝对时一样。
Is it possible with pure css?纯CSS可以吗? Or do I need some jQuery / JS?还是我需要一些 jQuery / JS?
body { background: #f0f0f0; text-align: center; } .parent { max-width: 300px; height: 300px; margin: auto; position: relative; background: white; } p { padding: 20px; } #banner { padding: 20px; background: black; color: white; }
<div class="parent"> <p>My relative parent container,<br>with a fixed width.</p> <div id="banner"> My full width banner </div> <p>...</p> </div>
Anyone has any experience in getting this to work?任何人都有让这个工作的经验吗? Any and all tips are much appreciated.非常感谢任何和所有提示。 Thanks!谢谢!
Yes, you can use 100vw width.是的,您可以使用 100vw 宽度。 To correct the position, you can add margin-left: calc(-50vw + 50%);
要更正位置,可以添加margin-left: calc(-50vw + 50%);
, which moves it half of the screen width to the left and then back 50% of its own width to the right, thereby "centering" it again, which in this case results in a full-width element: ,它将屏幕宽度的一半向左移动,然后将其自身宽度的 50% 向右移动,从而再次“居中”它,在这种情况下会产生一个全宽元素:
body { background: #f0f0f0; text-align: center; } .parent { max-width: 300px; height: 300px; margin: auto; position: relative; background: white; } p { padding: 20px; } #banner { padding: 20px; background: black; color: white; width: 100vw; margin-left: calc(-50vw + 50%); }
<div class="parent"> <p>My relative parent container,<br>with a fixed width.</p> <div id="banner"> My full width banner </div> <p>...</p> </div>
There is one problem remaining however: As soon as the contents are longer than the window height, a horizontal scrollbar will appear.但是还有一个问题:只要内容长于窗口高度,就会出现一个水平滚动条。 I previously brought up that problem in this question , but I haven't really found a solution or got a satisfying answer for it.我之前在这个问题中提出了这个问题,但我还没有真正找到解决方案或得到令人满意的答案。
I use relative
with margin
and left
right
to achieve this我使用relative
right
margin
和left
来实现这一点
body { background: #f0f0f0; text-align: center; overflow: hidden; } .parent { max-width: 300px; height: 300px; margin: auto; position: relative; background: white; } p { padding: 20px; } #banner { padding: 20px; background: black; color: white; width: 100vw; position: relative; left: 50%; right: 50%; margin-left: -50vw; margin-right: -50vw; }
<div class="parent"> <p>My relative parent container,<br>with a fixed width.</p> <div id="banner"> My full width banner </div> <p>...</p> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.