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.
#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
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 .
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.
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.
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.
Try below css for img
.
height: 100%;
for maximum heightdisplay: block;margin: auto;
for centeringmax-width: 100%;
to fit large imagesPlease 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With