简体   繁体   English

CSS位置固定与相对父级相同的大小

[英]CSS position fixed same size as relative parent

I would like to have kind of a sticky section which has a fixed position at the top when the user scrolls through the page.我想要一种粘性部分,当用户滚动页面时,它在顶部有一个固定的位置。

If I set the width to 100% of the sticky container it overflows the parent div container.如果我将宽度设置为粘性容器的 100%,它会溢出父 div 容器。 The width should be exactly the same even if I resize the browser.即使我调整浏览器的大小,宽度也应该完全相同。

You can see my problem here: https://jsfiddle.net/d49tyfo2/2/你可以在这里看到我的问题: https ://jsfiddle.net/d49tyfo2/2/

 body { padding: 50px; } #d-header { height: 400px; position: relative; padding-bottom: 55px; background-color: blue; margin-bottom: 0px !important; box-shadow: 2px 5px 3px 0 rgba(0,0,0,0.16); z-index: 1; } .tab-container { position: absolute; width: 100%; bottom: 10px; height: 55px; letter-spacing: 1px; } .tabs { background-color: orange; color: white; text-transform: uppercase; width: 26.8%; height: 50px; line-height: 50px; float: left; text-align: center; margin-left: 10px; } .date { position: absolute; font-size: 72px; text-align: center; left: 0; right: 0; bottom: 65px; } .header-sticky { position: fixed; top: 83px; width: 100%; height: 205px; background-color: white; box-shadow: 0 5px 4px 0 rgba(0,0,0,0.16),0 0px 0px 0 rgba(0,0,0,0.12); border: 1px solid black; }
 <body> <div class="myHeader" id="d-header"> <div class="special-headline-wrap" style="width: 526px;"> <h1 class="special js-done">HEADLINE</h1> </div> <p>Aenean lacinia nulla sed consectetur. Cras mattis consectetur purus sit amet fermentum. Maecenas faucibus mollis interdum.</p> <div id="date-tab-wrapper" class="header-sticky"> <div class="date">2017</div> <div class="tab-container"> <div class="tabs" style="margin-left: 9.1%;">Tab 1</div> <div class="tabs">Tab 2</div> <div class="tabs">Tab 3</div> </div> </div> </div> </body>

What I am missing here?我在这里缺少什么?

Elements that are position: fixed are removed from the document flow, and are therefore not subject to their parent containers. position: fixed的元素将从文档流中移除,因此不受其父容器的约束。 From CSS Tricks:来自 CSS 技巧:

position: fixed - the element is removed from the flow of the document like absolutely positioned elements. position: fixed - 元素像绝对定位元素一样从文档流中移除。 In fact they behave almost the same, only fixed positioned elements are always relative to the document, not any particular parent, and are unaffected by scrolling.事实上,它们的行为几乎相同,只有固定定位的元素总是相对于文档,而不是任何特定的父元素,并且不受滚动的影响。

Try width:100vw, which is the viewport relative unit for width.试试 width:100vw,这是宽度的视口相对单位。 By switching to viewport units it worked for me synchronizing two elements of which one was position:fixed.通过切换到视口单位,我可以同步两个元素,其中一个元素是位置:固定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM