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>
<img src=""></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

2

4 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> <img src="" alt="">
</div>
<div> <img src="" alt="">
</div>
1

Just add:

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

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%;
}
#avatar { float: left; width: 50%; height: 300px; border: 1px solid black;
}
#avatar img { /*width: 100%;*/ height: auto; max-width: 100%; height:100%;
}
<div>
<img src=""></div>

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like