Home > Net >  CSS :- Dynamically compute header's height and then place elements below it
CSS :- Dynamically compute header's height and then place elements below it

Time:09-19

I want to keep my header fixed in place like this: enter image description here

And then I want to add the body content below the header:

<div>
      <Header />
      <br />
      <br />
      <br />
      <br />
      <div style={{ color: 'red', zIndex: 101 }}>Hello World</div>
    </div>

However in order to keep this responsive, I can't just go with some manual calculation like marginTop: '10rem' as based on different screen sizes it may vary. I want to know what's the best way around to deal with this?

Here's how I have styled my header:

.Header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background: $light-bg;
  box-shadow: -4px 4px 10px 7px rgba(0, 0, 0, 0.25);
  padding: 0 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  animation-duration: $background-animation-duration;
  animation-name: animateFadeEffectLight;
  animation-timing-function: ease-in;
  &_dark {
    background: $toggle-switch-color-dark;
    animation-duration: $background-animation-duration;
    animation-name: animateFadeEffectDark;
    animation-timing-function: ease-in;
  }
}

enter image description here

Here's how my layout looks like:

 <div>
      <Header />

      <div style={{ color: 'red', zIndex: 101 }}>Hello World</div>
    </div>

CodePudding user response:

If you want the header with fixed height and content height takes all of the reset space:

e.g. header's height is 60px, and content's height could be set to:

calc(100vh - 60px);

https://developer.mozilla.org/zh-CN/docs/Web/CSS/calc

CodePudding user response:

Instead of position:fixed; you can use position:sticky; to the header element. So it is positioned based on the user's scroll position.

Note: A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).

.Header {
  ...
  position: sticky; // Instead of fixed
}

If you add this style property, on page loads the header will be position:relative; after page scroll happens it will change automatically to position:sticky; similarly fixed.

  •  Tags:  
  • css
  • Related