Img using `object-fit: cover` still increases height of parent

782 Views Asked by At

I'm building a component that will have variable content. So I'd like the img to respond like a bg img, taking the height of it's container rather than defining the height. Even when I define add object-fit: cover though, the img still affects the height of it's parent. I want the text to define the height of the parent, not the img. I would prefer not to use a background img as the image is populated via a wysiwyg editor and I don't have control over where the uploaded img is loaded (ie. it has to be an img). Thanks for your help.

Codesandbox

CODE:

.container {
    display: flex;
    flex-direction: row;
    padding: 20px;
    background: lightblue;
    width: 80%;
}

.img-item {
    align-self: stretch;
    flex-shrink: 2;
}

.img-item img {
    object-fit: cover;
    height: 100%;
    width: 100%;
}

.text-item {
    flex-shrink: 3;
    padding: 20px;
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Static Template</title>
        <link rel="stylesheet" href="style.css" />
    </head>
    <body>
        <div class="container">
            <div class="img-item">
                <img src="https://i.imgur.com/2bvab7y.jpg" alt="" />
            </div>
            <div class="text-item">
                <h1>
                    Heading one
                </h1>
                <p>Hello world. You're the best.</p>
            </div>
        </div>
    </body>
</html>

1

There are 1 best solutions below

0
On

you are missing the flex-basis CSS property

.container {
  display: flex;
  flex-direction: row;
  padding: 20px;
  background: lightblue;
  width: 80%;
}
.img-item {
  align-self: stretch;
  flex-shrink: 2;
}
.img-item img {
  object-fit: cover;
  height: 100%;
  width: 100%;
}
.text-item {
  flex-shrink: 3;
  padding: 20px;
}
[class$=item]{flex-basis: 120px;}
<div class="container">
  <div class="img-item">
    <img src="https://i.imgur.com/2bvab7y.jpg" alt="" />
  </div>
  <div class="text-item">
    <h1>
      Heading one
    </h1>
    <p>Hello world. You're the best.</p>
  </div>
</div>