2017-02-16 131 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层次结构。一旦滚动将它从视口中取出,就使其“固定”。这是最典型的方法,如果高度可能变化,您始终希望始终显示标题。