Wrap image inside a div element

I have an image which i want to wrap completely inside div element. I have projects screenshots which i want to wrap inside div elements with class portfolioImg. No matter what the dimensions of my project image are, i want that it should fit in div elements perfectly. I am using Bootstrap4. Thanks !!
Codepen Link: https://codepen.io/shaan046/full/vWmVNY/

Assuming the div the image is wrapped in has some kind of size:

.my-image { object-fit: cover; }

Will fit the image completely in the div, keeping the aspect ratio but cropping any overlap.

It’s easier to just make sure the images are all the same size at first though, because then you don’t need to do anything.

Hey @shaan046,

The quickest way to solve your problem is to set the width of the image to 100%. So you might have something like:

<div class="image-wrapper">
  <img src="https://cool-image.com" alt="image">

// CSS
img {
  width: 100%;

The problem with this solution is that you’re serving the same image to users regardless of their device. On large viewports a smaller image could appear pixelated. On smaller viewports you might be serving users a larger image than necessary, which can slow down page speed.

If you’re building a responsive site, ideally you should implement responsive images using a combination of the <picture>, <srcset>, and <source> tags and the sizes attribute.

If you implement responsive images you can server images that fill their containers, and you will serve the right image to your users given their context.

If you want to deep dive on responsive images, here is a link to the guide I used to learn it.

I would avoid @DanCouper’s solution. object-fit doesn’t address the problem of serving a single image to users regardless of their device. Also, IE11 (or lower) doesn’t support object-fit and IE Edge only offers limited support ( https://caniuse.com/#feat=object-fit ).

IE is the only place object fit won’t do what it’s supposed to do in this case, and I don’t think serving different images is needed in this case, but you’re right re ignoring that. I was assuming he had a set of images all different sizes. It’s a good solution for some things but possibly not in this basic case.

I think best solution is just make sure the images are all the same size, then apply 100% width: for this, that’s all that’s needed. Using multiple srcs overcomplicates things at this stage; that’s an optimization, whereas this is just getting something that works well onto the page. So

.my-img {
  width: 100%;
  /* Images default to being inline, inline items cannot have a width, so change to block: */
  display: block;
  /* The following may be needed if there's still a wierd looking 2-3px gap at the bottom of the image in some browsers: */
  vertical-align: bottom;

Should be fine here