Reputation: 10512
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:
div
5px taller than the inner image?Surprisingly, this happens in
while IE7 renders it correctly, matching the height of the div
with the height of the image.
Upvotes: 6
Views: 3335
Reputation: 4215
I think you should set align
property to force the browser to show the img
tag correctly.
<div id="wrapper">
<img align="center" src="http://openclipart.org/image/800px/svg_to_png/74557/rally-car.png" />
</div>
Upvotes: 0
Reputation: 10512
OK, fiddling about, I found a good possible solution:
#wrapper img {
display: block;
width: 100%;
border: 1px dashed red;
}
Changing from the default inline
display to a block
display eliminates the line-height
problem straight away.
This approach is also semantically correct because in this case what we really want is a single image wrapped in a div
without any other elements in it, so the concept of line-height
needs to be completely wiped off by displaying the image as a block.
It works on all major browsers: Demo
Upvotes: 2
Reputation: 32192
Add vertical-align: top
in your img
tag's CSS as follows:
#wrapper img {
width: 100%;
border: 1px dashed red;
vertical-align: top; // Add this line
}
Upvotes: 1
Reputation: 13371
Check this demo out. It's a line-height
issue.
You need:
#wrapper {
width: 60%;
background-color: #aaa;
margin: 50px auto;
line-height: 0;
}
#wrapper img {
width: 100%;
border: 1px dashed red;
box-sizing: border-box;
}
I used box-sizing
to make sure the width
of the image doesn't overflow the container.
Upvotes: 2
Reputation: 15219
Your issue is that an image -- the <img>
tag, to be exact -- is an inline element. All you need to do is set display: block
on the image and the extra padding goes away. Demo.
Upvotes: 0
Reputation:
I think is because it doesn't see as a Table
i added the display:table in your code
And it looks fine now, check the link
Upvotes: 0