Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
CSS margin-top that changes in function of another element's height

I'm creating a website with a header that has position: fixed; so that it doesn't move when you scroll the page. However, I also need the main content to be visible but with the fixed element, we cant see the main content. Basically, I first tried to use a margin-top with a certain amount of pixels but then when I resize the window, it stays like that.

What I did was that using Javascript I made it that the margin-top of the main element is equal to the height of the header:

<div class="head" id="head">
</div>
<div class="item main" id="main">
</div>
function margintopchange() {
  var main = document.getElementById('main');
  var head = document.getElementById('head').getBoundingClientRect();
  newhead = head.height.toString();
  main.style.marginTop = newhead + "px";
  console.log(head.height);
  console.log(main.style.marginTop);
}

window.onresize = margintopchange();

Also the window.onresize doesn't work

And here is my CSS

.head{
    position: fixed;
    width: 100%;
    border: solid #2196F3 5px;
}
.main {
    grid-area: "main";
    margin: 0px;
}

The problem is that the margin-top doesn't update every time I resize the window but changes every time I reload the page.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I solved the problem with the help of Nullish Byte's comment. If anyone wants to know, it works if you do:

function marginheader() {
  var main = document.getElementById('main');
  var head = document.getElementById('head').getBoundingClientRect();
  newhead = head.height.toString();
  main.style.marginTop = newhead + "px";
}

window.addEventListener('resize', function(event) {
  marginheader()
}, true);

marginheader() 
//this is so that there is a margin at the beginning
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!