PDA

View Full Version : Set one element width equal to another



Rain Lover
06-13-2011, 08:21 PM
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

jscheuer1
06-13-2011, 09:34 PM
It's fine as long as the image is loaded, which it should be window.onload, unless there was a problem with the image.

Rain Lover
06-14-2011, 09:17 AM
It's fine as long as the image is loaded, which it should be window.onload, unless there was a problem with the image.

Thanks, John!

jmarren
06-14-2011, 08:50 PM
So why use javascript for this? Because you can achieve this effect with CSS easily. I think if you do this

.image-wrapper-div {
display:inline-block;
clear:both;
}

that should create a div that wraps around your image like an inline element, but it will still break. display: inline-block should cause your div to wrap around the image, while clear:both will make it clear the way a div should. Hope this helps

P.S. Also I think display:inline will do the trick too!

Rain Lover
06-16-2011, 06:31 PM
So why use javascript for this? Because you can achieve this effect with CSS easily. I think if you do this

.image-wrapper-div {
display:inline-block;
clear:both;
}

that should create a div that wraps around your image like an inline element, but it will still break. display: inline-block should cause your div to wrap around the image, while clear:both will make it clear the way a div should. Hope this helps

P.S. Also I think display:inline will do the trick too!


Thanks a lot! inline-block does the trick! :)