P Clegg
P Clegg

Reputation: 697

Image auto height to scaled width

I have certain images that are smaller in width which i stretch the width to fit the container, however would like the hieght to scale up as well, thanks in advance, Phil

Upvotes: 1

Views: 60

Answers (2)

Allan
Allan

Reputation: 261

There is no need to specify the height.

Take a look to my example, here is my jsfiddle

http://jsfiddle.net/d575tr49/

Here is the HTML

<div class="ele">
    <img src="http://viralstash.net/wp-content/uploads/2014/03/521013543_1385596410.jpg" border="0" />
</div>

Here is the CSS

.ele {
    outline: red solid 1px;
    width: 250px;
}
.ele img {
    width: 100%;
    display: block;
}

If you control the width on the Parent element, just the with, you will not need to worry about the width and height values of the image.

The image it self will set its width using the parents size, and by default the height value will be proportional to the width, so no need to specify the height value at all, not even in the parent.

Upvotes: 1

Remy Sheppard
Remy Sheppard

Reputation: 247

In your css:

img {
    width: 100%;
    height: auto !important;
}

CSS can naturally handle this. The image will automatically take up 100% of the width of its container, and the height will scale to match.

Upvotes: 2

Related Questions