ValarDohaeris ValarDohaeris - 2 years ago 581
Javascript Question

Chrome returns 0 for offsetWidth of custom HTML element

While trying to create an Angular directive that adapts the size of its content to the size of the container, I stumbled over the following issue:

Minimal HTML snippet:

<my-tag id="testWidth">
<div>some text</div>

When reading the width of
, I get a result of
in Chrome, whereas Firefox returns the correct result. In Chrome, the result is also correct if I replace

This is the expression I use to get the width:


As far as I know,
should be a valid custom element name. Is there anything else that I am doing wrong, or is this simply a bug in Chrome?

Chrome version: 49.0.2623.112 m

jsfiddle for quick testing

I am trying to understand if the behavior of Chrome is correct or if this is a bug.

The MDN documentation says:

The HTMLElement.offsetWidth read-only property returns the layout
width of an element.

As far as I can tell, it does not say that this only applies to elements with block display. And I also back my understanding by the fact that Firefox returns what I expect.

The same difference in behavior can also be observed for
tags, see this fiddle.

Answer Source

You need to style my-tag element with display: block

Here's fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download