I have a span with some text inside it.
document.getElementById('span1').scrollWidth;
on firefox return '100' as the scrollWidth but Chrome returns only '0'. Does Chrome not support this 'scrollWidth' property? Any other browser which doesnt support the same?
Also what would be work around for this if I need to get the length of a sentence in pixels?(I keep populating 'span1' with sentences using 'innerHTML' property)
I have a span with some text inside it.
document.getElementById('span1').scrollWidth;
on firefox return '100' as the scrollWidth but Chrome returns only '0'. Does Chrome not support this 'scrollWidth' property? Any other browser which doesnt support the same?
Also what would be work around for this if I need to get the length of a sentence in pixels?(I keep populating 'span1' with sentences using 'innerHTML' property)
Share Improve this question asked Nov 5, 2012 at 5:16 Bhumi SinghalBhumi Singhal 8,30711 gold badges52 silver badges79 bronze badges 2- <span id="span1" style="display:block">Bhumika</span> this when accessed using document.getElementById('span1').scrollWidth; gives the plete width of the page. This is different than the behaviour at firefox which provides the width of "bhumika" as the span's scrollWidth. – Bhumi Singhal Commented Nov 5, 2012 at 6:03
- Setting the display=block;visibility=hidden wont work if done manually ..in the least it didn't for me. – Bhumi Singhal Commented Nov 5, 2012 at 7:46
1 Answer
Reset to default 3There is a lot of difference in how Firefox and Chrome respond to css and js. [ff=Firefox, c=Chrome, sw= scrollWidth ]
Key points:
- sw works only when the element's
display
is notinline
andnone
.
ff sets thedisplay
toblock
by default while c sets it toinline
. So you would not get sw in c. If you need the element to be hidden anyways just use:
visibility:hidden
without setting thedisplay
for both ff and c. - If u have set the
visibility
in c, usestyle.width
of the element instead of sc. This works.
If you still want to use sc on chrome also for a hidden span
, you could use
@AnthonyWJones answer on
Knowing how wide a text line will be in HTML for word wrap and other applications
Worked for IE7,8,9 , FF, Chrome.