Reputation: 559
I have a div
to which I append different images with different sizes.
How can I set its size to be the same with the image's size.
For example if the size of the image is 640*480
the div
size is the same. If the next image is 1024*768
the div
size automatically changes to 1024*768
Thanks
Upvotes: 0
Views: 77
Reputation: 1870
Javascript:
function loadBackground(img) {
newBg = document.createElement('IMG');
newBg.src = img;
bgContainer = document.getElementById('background-container');
bgContainer.appendChild(newBg);
newBg.onload = function() {
imgs = bgContainer.getElementsByTagName('IMG');
bgContainer.style.width = newBg.offsetWidth;
bgContainer.style.height = newBg.offsetHeight;
bgContainer.removeChild(imgs[0]);
}
}
HTML:
<div id='background-container'>
<img src='image0.jpg'>
</div>
<a href='javascript: loadBackground("image1.jpg");'>Image 1</a>
Upvotes: 0
Reputation: 8338
div
is a block level element so will be full width, making it wider than the image. To get around that you could add div {float: left}
to your CSS. Also, add img {display: block}
to ensure the image fits flush in the div in terms of height
Upvotes: 1