aurel
aurel

Reputation: 3132

How to get a div containing and image element to have the same height as the image

I have this html code:

<div>
    <img src="http://placehold.it/319x300" alt="">
<div>

and this css:

*{margin: 0; padding: 0;}
div{
    background: red;
    width: 319px;
    height: auto;
}
img{
    width: 100%;
    height: auto;
}

However the background color of the div shows at the bottom. Is there a way make the container be the same height as the image? On the site I am working on, I have Erics Reset styles and also there is no padding or margin that conflicts with this. This is the sample code http://jsfiddle.net/ESmZW/1/ Thanks

Upvotes: 0

Views: 683

Answers (4)

Sean Hockabout
Sean Hockabout

Reputation: 5

@aurel If all you wanted was to have the div be the size of your image, why not set it's height and width to the size of your image? Your HTML also doesn't close your div. See my modifications on jsfiddle.

<div>
    <img src="http://placehold.it/319x300" width="319" height="300" alt="">
</div>

body {
    margin:0;
}


div {
    background: red;
    width: 319px;
    height: 300px;
}

Upvotes: 0

Petar Ivanov
Petar Ivanov

Reputation: 93090

You can use absolute/relative positionning:

*{margin: 0; padding: 0;}
div{
    position:relative;
    background: red;
    width: 319px;
    height: auto;
}
img{
    position:absolute;
    width: 100%;
    height: auto;
}

Upvotes: 0

Billy Moat
Billy Moat

Reputation: 21050

Set "display:block" on the image.

img {
    width: 100%;
    height: auto;
    display: block;
}

Upvotes: 0

j08691
j08691

Reputation: 208002

A quick way is to add the vertical-align:top property to the image

img{
    width: 100%;
    height: auto;
    vertical-align:top;
}

jsFiddle example

You could also float the image left and add the overflow:auto rule to the div like in this jsFiddle example.

Upvotes: 2

Related Questions