2017-10-12 196 views
0

我想有一种粘性部分,当用户滚动浏览页面时,顶部有一个固定的位置。CSS位置固定为相对父母相同的大小

如果我将宽度设置为粘性容器的100%,它会溢出父级容器。即使调整浏览器大小,宽度也应该完全相同。

你可以在这里看到我的问题: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>

我是缺少在这里?

+0

那么,如果它坚持在屏幕上的位置,它总是会以某种方式溢出其他内容。我不完全明白你想要达到的目标。 * what *的宽度应该始终相同? – mumpitz

+0

@mumpitz'date-tab-wrapper'(固定的)的宽度应该与'd-header'相同 – Marlon

+1

是的,很确定你不能这么做。固定位置元素**总是**与视口相关,并忽略任何父宽度等。也许'position:sticky'可能是一个选项。否则,你可能需要JS。 –

回答

0

从文档流中删除position: fixed的元素,因此不受其父容器的限制。 来自CSS技巧:

位置:固定 - 从绝对定位元素的文档流中删除该元素。事实上,它们的行为几乎相同,只有固定的定位元素总是相对于文档而不是任何特定的父元素,并且不受滚动的影响。