Home > Software engineering >  Get heights of loaded elements and add css rule
Get heights of loaded elements and add css rule

Time:11-21

I have a number of differently sized elements on a page all with the same class of .margin-top-auto

I cannot know the heights of the elements until the page loads.

I need to add {margin-top = the height of each element} to these elements on page load.

Looking for a jQuery/Vanilla snippet that would accomplish this for me.

Many thanks.

CodePudding user response:

You can get the element's offsetHeight:

const height = div.offsetHeight;

div.style.marginTop = height   'px'

console.log(height)
#div{
  background-color:black;
  height:100px;
  width:100px;
}
<div id="div"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

To target multiple elements, you can do:

document.querySelectorAll('.margin-top-auto').forEach(e => e.style.marginTop = e.offsetHeight   'px')
.margin-top-auto{
  height:100px;
  width:100px;
  background-color:black;
}

.row{
  display:flex;
}
<div class="row">
<div class="margin-top-auto"></div>
<div class="margin-top-auto"></div>
<div class="margin-top-auto"></div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related