Reputation: 1530
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>
Upvotes: 1
Views: 771
Reputation: 53709
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;
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>
Upvotes: 2
Reputation: 299
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.
Upvotes: 2