rufus
rufus

Reputation: 857

Image overflowing div advice

Im sure this is really easy but i have been looking at this issue for a little while and my brain has gone blank. I have a div that then has an image inside of it. The image seems to just overflow the div border and its driving me mad. I have an image below to show you what is happening along with the css.

image

#avatar {
  float: left;
  width: 50%;
  height: 300px;
  border: 1px solid black;
}

#avatar img {
  width: 100%;
  height: auto;
}
<div id="avatar">
<img src="http://i.imgur.com/dkzoNCc.png"></div>

I have a border on the main div #avatar just so i can see the whole size of the div. All i want is for the image to scale to the size of the div. If i set the height to 100% it goes into the div just fine but when resizing it it starts to overflow the div. I want the image to resize on the width not height.

Am i missing something really simple here? I dont want to use overflow hidden on the image as that will just cut some of it off i believe.

Thanks everyone

Upvotes: 20

Views: 58723

Answers (4)

user6768630
user6768630

Reputation:

#avatar {
  float: left;
  width: 50%;
  height: 300px;
  border: 1px solid black;
}

#avatar img {
  /*width: 100%;*/
  height: auto;
  max-width: 100%;
  height:100%;
}
<div id="avatar">
<img src="http://i.imgur.com/dkzoNCc.png"></div>

Upvotes: 2

Felix A J
Felix A J

Reputation: 6470

Try below css for img.

  • use height: 100%; for maximum height
  • display: block;margin: auto; for centering
  • max-width: 100%; to fit large images

Please check the example with large and small images.

#avatar {
  float: left;
  width: 50%;
  height: 300px;
  border: 1px solid black;
}
#avatar img {
height: 100%;
max-width: 100%;
display: block;
margin: auto;
}
<div id="avatar">
  <img src="http://www.baraodasfestas.com.br/Assets/Produtos/SuperZoom/0431_MICKEY_635703672330071491.jpg" alt="">
</div>
<div id="avatar">
  <img src="https://upload.wikimedia.org/wikipedia/en/d/d4/Mickey_Mouse.png" alt="">
</div>

Upvotes: 17

Sidharth Gusain
Sidharth Gusain

Reputation: 1501

It's because of your height:auto for the <img>

Just use :

#avatar img 
{
  width: 100%;
  height: 100%;
}

But this will stretch you image. So if you want full size image inside your container you need to stretch your container instead. Like

#avatar 
{
  float: left;
  display: inline-block;
  width: 50%;
  height: auto;
  border: 1px solid black;
}

#avatar img 
{
  width: 100%;
  height: 100%;
}

Upvotes: 1

Krešimir Galić
Krešimir Galić

Reputation: 376

Just add:

#avatar img {
  max-width: 100%;
}

Upvotes: 10

Related Questions