Can I easily "set" an element's offsetWidth?

Stephen picture Stephen · Feb 2, 2011 · Viewed 14k times · Source

Note: I know offsetWidth is read only

I'm trying to make a pop-up 'div' overlay a tr element with the exact same width.

However, I am stumped as to how to set my div's width so that its offsetWidth is the exact same as the tr.

The calculation would look something like:

div.width = tr.offsetWidth - div.paddingWidth - div.marginWidth

but surely there's a better way (since I can only think of getting the padding and margin offsets in groups of two...)

Specifically, I'd like an answer for YUI 2 if possible.

Answer

Simon Lieschke picture Simon Lieschke · Feb 2, 2011

If you zero out your div's margin and paddings then something like the following should work:

YAHOO.util.Dom.setStyle(div, 'width', tr.offsetWidth + 'px');

Depending on how you are dealing with borders on your div and tr you may want to assign tr.clientWidth instead.

You can then set any margin/paddings as required on the parent/child elements of your div to achieve the desired appearance.

The key to working out what you'll want to do is understanding exactly what clientWidth and offsetWidth measure, and that the CSS width of an element is its content area and excludes any margin, border, and padding defined on it (see the W3C box model here).

You could include the padding etc. in your calculation by querying it from the