2017-10-12 79 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技巧:

位置:固定 - 從絕對定位元素的文檔流中刪除該元素。事實上,它們的行爲幾乎相同,只有固定的定位元素總是相對於文檔而不是任何特定的父元素,並且不受滾動的影響。