4

I am trying to find a solution without having to use background-image, but being able to use an inline <img>.

I would like to make it so that if the image container's dimensions are not the same as the image, the image will still fill the width and height of the container, cropping whatever part it has to.

Also, if a part of the image is smaller than the container, it will stretch over 100% to fill the container.

In the example below, I have a huge image that can easily fill the width and height of the container. The container is a different aspect ratio from the image, so I end up with blank space, either horizontally or vertically. I want to fill that container no matter what, even though part of the image will be cropped away.

class[*='container'] {
  margin-bottom: 50px;
}
.container img {
  width: 20%;
  height: 20%;
}
.container-1 {
  background: #f0f0f0;
  width: 400px;
  height: 150px;
}
.container-1 img {
  object-fit: cover; 
  max-width: 100%;
  max-height: 100%;
}
.container-2 {
  background: #f0f0f0;
  width: 150px;
  height: 400px;
}
.container-2 img {
  object-fit: cover; 
  max-width: 100%;
  max-height: 100%;
}
<p>Original image:</p>
<div class="container">
  <img src="https://themetry.com/wp-content/uploads/pug.jpg" />
</div>

<p>Container 1:</p>

<div class="container-1">
  <img src="https://themetry.com/wp-content/uploads/pug.jpg" />
</div>

<p>Container 2:</p>

<div class="container-2">
  <img src="https://themetry.com/wp-content/uploads/pug.jpg" />
</div>
MultiDev
  • 10,389
  • 24
  • 81
  • 148

1 Answers1

4
.container-1 img {
    object-fit: cover;
    /* max-width: 100%; */
    /* max-height: 100%; */
    width: 100%;
    height: 100%;
}

class[*='container'] {
  margin-bottom: 50px;
}
.container img {
  width: 20%;
  height: 20%;
}
.container-1 {
  background: #f0f0f0;
  width: 400px;
  height: 150px;
}
.container-1 img {
  object-fit: cover;
  width: 100%;
  height: 100%;
}
.container-2 {
  background: #f0f0f0;
  width: 150px;
  height: 400px;
}
.container-2 img {
  object-fit: cover;
  width: 100%;
  height: 100%;
}
<p>Original image:</p>
<div class="container">
  <img src="https://themetry.com/wp-content/uploads/pug.jpg" />
</div>

<p>Container 1:</p>

<div class="container-1">
  <img src="https://themetry.com/wp-content/uploads/pug.jpg" />
</div>

<p>Container 2:</p>

<div class="container-2">
  <img src="https://themetry.com/wp-content/uploads/pug.jpg" />
</div>

Since you're already using object-fit, I used it in my answer, as well. Just keep in mind it's not supported by IE / Edge. Here are some workarounds: https://stackoverflow.com/a/37127590/3597276

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701