Sidney Sousa
Sidney Sousa

Reputation: 3584

How to give height to an image without stretching

I have an image with which has a very high resolution. I set the width to 100% and it works fine. The only problem is that its too big in height I'm not being able to give a height without stretching the image.

Here my HTML:

<div class="container">
  <div class="image">
    <img src="Post1.jpg" alt=""> 
  </div>
</div>

CSS:

.div{
  max-height:500px
}
img{
  width:100%;
  height:auto;
  max-height:100%;
}

How can I give it proper height without stretching the image?

Upvotes: 0

Views: 3001

Answers (3)

Smit
Smit

Reputation: 2138

/* css */
    div{
      height:500px;
      width: 100%;
    }
    img{
      width: auto;
      height: auto;
    }

<!-- HTML -->
<div class="container">
  <div class="image">
    <img src="Post1.jpg" alt=""> 
  </div>
</div>

Upvotes: 0

Rob Monhemius
Rob Monhemius

Reputation: 5144

Ok, there are several flaws in your code.

  1. The .div selector selects anything with class="div". You want to use the .container selector
  2. You forgot to close max-height:500px with a ;
  3. Finally the answer to you question: Your image still shows in the original size. this is because you haven't set overflow: hidden; By adding this line the image does not display outside of the .container div.

I tried to stick as close to the original post as possible. Keep in mind you are cutting off a part of the image which may lead to undesired results.

html

<div class="container">
  <div class="image">
    <img src="Post1.jpg" alt=""> 
  </div>
</div>

css

.container{
  max-height:500px;
  overflow: hidden;
}
img{
  width:100%;
}

Upvotes: 0

Dhruvi Mistry
Dhruvi Mistry

Reputation: 122

You can try this..add image instead of inner div, If you have to give width 100%.

.sq1 {
   height : 300px;width:300px;
  background-color:#eee;position:fixed;
}

.sq2{
  height:200px;width:200px;
  background-color:#000;margin:50px auto;
}
<div class="sq1">
  <div class="sq2"></div>
</div>

Upvotes: 1

Related Questions