CSS Position Fixed Removes Spacing

So I was trying to format a header using some CSS so that it travels as the user scrolls through the page (clicking it returns users to the previous screen so I want them to be able to access it without having to scroll), and I tried setting it as “position: fixed”, and it completely removed the spacing it had from the elements below it, so in its default position it now overlaps the first elements below it. Is there any way to set some sort of fixed position for the header, while also maintaining the spacing it had with the elements below it? I know that setting “Position: fixed” removes it from the document flow, but is there a way to still make the spacing work? Thank you!
2 answers

You don’t set the ‘position: fixed’ in CSS. You have to do it using javascript. The sample is given below.

var header = document.getElementById("header").offsetTop;
  var docTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  var adHeight = Number(getStyleValue(elem, "height").replace("px", ""));
    if ((header - docTop) < 60) {
      elem.style.position = "fixed";
      elem.style.top = "60px";
      document.getElementById("header").style.position = "sticky";

you should set the id in header tag then using the id we can set the position fixed while scrolling the page.


One option would be to give the next element below it (or the next container around those elements) a `top-margin: <amount in pixels>px`. Although, if it’s fixed, that may appear as a gap in the page when the user scrolls and the header moves with the page. If it’s at the top of the page, it shouldn’t be a problem.