How to add margin-top that is equal to the height of the element above that is positioned fixed on sibling element?

By default positioning, if everything’s positioned relative, the header will scroll together with the sibling below it, in this case i called it main, what if the header is positioned fixed with unknown height, the main automatically goes up, how do you add the margin-top value for the main that is equal to the header’s height without using Javascript? is it possible with pure css?

HTML:

<header>
    logo and navigation here
</header>
<main>
  content here
<main>

CSS:

header { position: fixed; width: 100%; z-index: 100; }
main { margin-top:  unknown value based on header's height }

If you use your browser’s developer tools, you can inspect your header, and see what the (automatically set) height is.

When I recreated your problem in codepen, the automatic height set was 68px, and no matter what margin-top I set for main, it always stayed together with the header.

I would use a flex-box for the header if you want it fixed.

1 Like