I want to wrap an image into an HTML div and since I want this to be fully scalable with the size of the window, I want to set the width of the div in percentage as follows:
HTML
<div id="wrapper">
<img src="http://openclipart.org/people/netalloy/rally-car.svg" />
</div>
CSS
#wrapper {
position: absolute;
width: 50%;
}
#wrapper img {
width: 100%;
}
The image should determine the height of its container. This is because the image width is set to 100% and the image height is calculated accordingly, maintaining the correct aspect ratio.
The result is visible on JSFiddle.
My questions are:
- Why do all modern browsers render the wrapper
div5px taller than the inner image? - How can I get rid of this 5px gap, while still setting all the sizes in percentage and without using JavaScript?
Surprisingly, this happens in
- Chrome (21.0.1180.89)
- Firefox (15.0.1) and
- IE8
while IE7 renders it correctly, matching the height of the div with the height of the image.
OK, fiddling about, I found a good possible solution:
Changing from the default
inlinedisplay to ablockdisplay eliminates theline-heightproblem straight away.This approach is also semantically correct because in this case what we really want is a single image wrapped in a
divwithout any other elements in it, so the concept ofline-heightneeds to be completely wiped off by displaying the image as a block.It works on all major browsers: Demo