Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda