Forum Moderators: open

Message Too Old, No Replies

Set one element width equal to another

         

Rain_Lover

8:35 pm on Jun 13, 2011 (gmt 0)

10+ Year Member Top Contributors Of The Month



Hi,

I'd like to set the div width equal to the image width. Here's what I can think of:

<script type="text/javascript">
window.onload = function ()
{
document.getElementById('foo').style.width = document.getElementById('bar').width + 'px';
}
</script>
<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!
Rain lover

daveVk

4:17 am on Jun 14, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



As the image is within the div, why is there a need to set the div width ?

The div width = image width + margins,padding etc, unless other css rules apply.

lexipixel

5:12 am on Jun 14, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Without setting a width I think the <div> will default to width:100% in some UA's --- at least from what I've seen, and sometimes causing float issues.

daveVk

7:25 am on Jun 14, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Check with CSS forum for a CSS solution if this is a CSS problem. Maybe width:auto ? Using script will conflict with (override?) CSS styling.

rocknbil

5:29 pm on Jun 14, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yeah if you are trying to float the div, then just float the image inside it - this will "shrink wrap" the div around the image.