简体   繁体   中英

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. 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. Is there a solution that respects changing heights of header without using javascript?

 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. I'd suggest not to use position at all but respect the html hierarchy. 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; 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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