简体   繁体   English

CSS位置:固定标头

[英]CSS position:fixed header

I have a fixed header with position:fixed why it stays on top of other elements and hides them, so I have to add padding to main. 我有一个带有position:fixed的固定标头position:fixed为什么它保留在其他元素之上并隐藏它们的原因,因此我必须在main.添加padding main. Because the height of header varies by content, font-size and padding set by media queries it's not possible to use a fixed value for padding as in the snippet. 由于header的高度随内容,媒体查询设置的字体大小和填充而变化,因此无法像代码片段中那样使用固定的padding值。 Is there a solution that respects changing heights of header without using javascript? 有没有一种解决方案,可以在不使用JavaScript的情况下改变header高度?

 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> 

There is no way you can achieve it without the use of Javascript if you want to keep the fixed position. 如果要保持固定位置,没有使用Javascript的方法是无法实现的。 I'd suggest not to use position at all but respect the html hierarchy. 我建议不要使用位置,而要尊重html层次结构。 And make it "fixed" once scrolling gets it out of the viewport. 一旦滚动将其移出视口,并使其“固定”。 This is the most typicall approach when you want to have the header visible at all times if height could vary. 如果您希望高度可以变化,则始终使标题可见,这是最典型的方法。

As others have said, you can't do it without javascript, but you can fake a fixed header using flexbox and flex-grow: 1; overflow-y: scroll; 正如其他人所说,没有javascript就无法做到,但是您可以使用flexbox和flex-grow: 1; overflow-y: scroll;伪造固定的标头flex-grow: 1; overflow-y: scroll; flex-grow: 1; overflow-y: scroll; on the main content area. 在主要内容区域。

 * {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> 

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

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