Home > Software design >  Can you measure HTML layout rendering in JavaScript without actually displaying the content?
Can you measure HTML layout rendering in JavaScript without actually displaying the content?

Time:10-11

I want to be able to measure and change the layout of an HTML element before I display it. For two examples where I want to do that are

  1. a two column layout which paginates on the actual window size
  2. a table format optimization, i.e., finding the optimal table width and height (my intuition is that minimizing the circumference of the table (height width) will be the optimal size.

I want that optimization to happen (in JavaScript) before I show the item, i.e., I don't want to show it and then shift around the content and size.

I noticed before the content gets shown, certain contentHeight measurements that I am doing are all zero. So only after displaying it will have real measurements.

Could I get proper measurements even if the content is hidden? (display: none)? Or maybe only if it is not hidden but still covered by something else?

CodePudding user response:

If you have a wrapper element act as a mask using overflow hidden and dimension of zero, the content inside will retain measurable dimensions while being hidden from sight.

<style>
  .masked {
    overflow: hidden;
    width: 0;
    height: 0;
  }
</style>

<div >
  <ul>
   <li>My temporary hidden content</li>
  </ul>
</div>

Everything else outside the masked wrapper will wrap around the collapsed space.


You have the potential here to use CSS animation to grow the width & height after you have set the layout you desire for a fancy reveal.

  • Related