Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image overflowing div advice

Tags:

html

css

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

like image 893
rufus Avatar asked Sep 01 '16 08:09

rufus


People also ask

How do I make an image not overflow in a div?

Give the container a fixed height and then for the img tag inside it, set width and max-height . The difference is that you set the width to be 100%, not the max-width .

How do I make a picture fit a div perfectly?

Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.

How do I fix an image overflow in CSS?

To show an image in an img element uncut, you use the object-fit: contain , set width and /or height to 100% and it will make both vertical and horizontal images fit with no overflow.

Why is my image bigger than the div?

The reason behind your issue is that you did not specify the width of the container but, in the same time, you set a width: 100%; for the image.


1 Answers

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>
like image 152
Felix A J Avatar answered Sep 19 '22 00:09

Felix A J