Move a div to an absolute position

Why might we want to do this?

One reason could be to make a menu which has drop down subsection divs. It would also be useful for many other problems.

How can we do this?

We can set the CSS position style to absolute. Then we can make use of the method getBoundingClientRect to find the co-ordinates of an element we want to move our div to. Then it’s just a bit of simple math to calculate where to move it to.

We can test this out in the Javascript console. First clear the styling and set up up some divs:

document.head.innerHTML =''; document.body.innerHTML = ` <div class="MENUitem">Company</div> <div class="MENUitem">Product</div> <div class="MENUitem">Resources</div> <div class="MENUitem">Contact</div> <div class="MENUdropdown"></div>`;

Then some basic CSS rules:

.MENUitem{ display: inline-block; border: black solid 1px; padding: 5px; } MENUdropdown { border: black solid 1px; height: 140px; width: 100px; }

Then define this helpful little function:

function MENUposition(Parent, Child){ var Rect = Parent.getBoundingClientRect(); Child.style.position = 'absolute'; Child.style.top = (Rect.top + Rect.height + 2) + "px"; Child.style.left = Rect.left + "px"; }

Get our array of menu items, the dropdown then use the MENUposition command to position the dropdown: