Tithos
Tithos

Reputation: 1417

CSS Image Resize by Height

I am aware of the image resizing technic of changing image proportions based on width:

img{
  max-width: 100%;
  height: auto;
}

I need to do the same thing only based on the height of the parent, not the width. I have tried the following with no effect:

img{
  width: auto;
  max-height: 100%;
}

I hope I explaining this well enough.

Please help :)

Upvotes: 2

Views: 721

Answers (3)

Shuhad zaman
Shuhad zaman

Reputation: 3390

i have tried this and it worked .

    <div class="parent">
    <img src="http://searchengineland.com/figz/wp-content/seloads/2014/07/google-logo-sign-1920-600x337.jpg" alt="..." />
</div>


.parent {
    width: 100%;
    height: 180px;
    overflow: hidden;
}

see it here https://jsfiddle.net/shuhad/vaduvrno/

Upvotes: 0

Naruto Dev
Naruto Dev

Reputation: 1003

max-height will only restrict the height to be less than the given value.

If you want it to be the same as its parent.. give it as height: 100%

hence this should work: CSS:

img{
  height: 100%; // changed max-height to height here
  width: auto; // this is optional
}

Upvotes: 1

bboysupaman
bboysupaman

Reputation: 1334

You cannot effectively base it on the height using standard css techniques, but you can make the height relate directly to the width of the image for a more flexible layout. Try this:

img {
    position: relative;
    width: 50%;     /* desired width */
}
img:before{
    content: "";
    display: block;
    padding-top: 100%;  /* initial ratio of 1:1*/
}

Upvotes: 1

Related Questions