rain_lover — 2011-06-13T16:29:21-04:00 — #1
I'd like to set the div width equal to the image width. Here's what I can think of:
window.onload = function ()
document.getElementById('foo').style.width = document.getElementById('bar').width + 'px';
<div id="foo" style="background:red;"><img id="bar" src="image.jpg"></div>
It seems to be working, but I'm not sure if it's correct coding.
Thanks in advance for checking the code or any improvement you suggest!
paul_wilkins — 2011-06-13T20:23:08-04:00 — #2
It works, but normally a div will automatically expand to fix the width of the content that's inside it, so you shouldn't need that script there at all, should you?
rain_lover — 2011-06-13T23:28:29-04:00 — #3
Thanks for the answer, but the div width is always larger than image width as it's a block element. I want them to be equal.
paul_wilkins — 2011-06-13T23:31:28-04:00 — #4
I just want to point out that using scripting for this is a heavy-handed technique compared with using CSS to achieve the the same result.
I'm glad it works out for you though.