Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong height of DIV image wrapper with percentage width values

Tags:

html

css

image

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: http://jsfiddle.net/lorenzopolidori/5BN4g/15/

My questions are:

  1. Why do all modern browsers render the wrapper DIV 5px taller than the inner image?
  2. 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.

like image 645
Lorenzo Polidori Avatar asked Oct 07 '22 13:10

Lorenzo Polidori


2 Answers

Check this out :

http://jsfiddle.net/5BN4g/29/

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

like image 118
Ahmad Alfy Avatar answered Oct 10 '22 01:10

Ahmad Alfy


................

Hi now add vertical-align:top in your img tag throw css

as like this

#wrapper img {
    width: 100%;
    border: 1px dashed red;
    vertical-align:top; // add this line
}

live demo

like image 24
Rohit Azad Malik Avatar answered Oct 10 '22 01:10

Rohit Azad Malik