2017-02-16 143 views
0

我有position:fixed爲什麼它停留在其它元件之上,並隱藏它們固定報頭,所以必須添加paddingmain.由於header高度由內容,字體大小和填充組變化通過媒體查詢,不能像片段中那樣爲padding使用固定值。有沒有一種解決方案可以在不使用JavaScript的情況下改變header的高度?CSS位置:固定報頭

body { 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 

 
header { 
 
    background-color: grey; 
 
    position: fixed; 
 
    width: 100%; 
 
} 
 

 
main { 
 
    padding-top: 80px; /* bad, because it's fixed */ 
 
}
<header> 
 
    <h1>Example</h1> 
 
</header> 
 
<main> 
 
    <p>Content</p> 
 
</main>

+0

使用 '時間' 80px的同等價值將解決字體大小相關的問題。 –

+0

是的,但不是其他問題。想象一下,你永遠不會知道'header'的高度...... – Hativ

+1

由於'position:fixed'的性質,我會猜測沒有純CSS的做法。 –

回答

2

正如其他人所說的,你不能沒有JavaScript,但你可以在主內容區使用flexbox和flex-grow: 1; overflow-y: scroll;來僞造一個固定頭。

* {margin:0;} 
 
body { 
 
    display: flex; 
 
    flex-direction: column; 
 
    max-height: 100vh; 
 
} 
 
section { 
 
    flex-grow: 1; 
 
    overflow-y: scroll; 
 
} 
 
main { 
 
    background: #eee; 
 
    min-height: 500vh; 
 
}
<header> 
 
    <h1>Example</h1> 
 
</header> 
 
<section> 
 
    <main> 
 
    <p>Content</p> 
 
    </main> 
 
</section> 
 
<footer> 
 
    <p>footer</p> 
 
</footer>

+0

這可以結合「節」後的粘腳?我也爲此使用了flexbox,但隨着您的更改不再適用。請參閱https://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/ – Hativ

+0

@Kiltarc您可以使用它的頁腳,它的行爲將與頁眉類似。更新了我的答案。 –

2

有沒有辦法可以實現它而不使用Javascript,如果你想保持固定的位置。我建議不要使用位置,但要尊重html層次結構。一旦滾動將它從視口中取出,就使其「固定」。這是最典型的方法,如果高度可能變化,您始終希望始終顯示標題。