Search code examples
javascripthtmlcssheadercss-position

Move whole html content of a page down?


I want to insert a header in a page using javascript. I don't want to hide anything from the original content but just to add a header above that is fixed. Have in mind I don't know the content of the page I'm trying to manipulate.

I tried adding a margin-top to the body element:

body{
  margin-top: 40px;
}

But if there are any elements with fixed position:

.header{
   position: fixed;
   top: 0;
}

They will remain on top of the page.

Do you have any suggestions?


Solution

  • A solution was to iterate over the elements and find out those with fixed position.

    function moveDownFixedElements(){
    let elems = document.body.getElementsByTagName("*");
    
    for (let i = 0; i < elems.length ; i++) {
        if (window.getComputedStyle(elems[i], null).getPropertyValue('position') === 'fixed') {
            let style = window.getComputedStyle(elems[i]);
            let top = style.getPropertyValue('top');
            top = parseInt(top) + 40 + "px";
            elems[i].style.top = top; 
        }
    }
    }
    

    Now without knowing the structure of the page I am able to insert something on top of it.

    EDIT: Another really simple solution is to use the transform property.

    document.body.style.transform = "translateY(40px)";