How do I force an img element to take the width and height of its parent?

Viewed 53

I'm trying to allow an image to take the height and width of its parent. Its parent is a grid item(div1) that has a height 100% of the container.

What I've expected and wanted:

  1. div1 will take the height of the parent(container) means div1 height should be 500px and a width of 50% of the container.
  2. The image should take the width and height of its parent(div1). Image should have a height of 500px and width 100% of its parent.

What the result shows:

  1. image took a height of 530px and the div1 took a height of 530px too.

I'm confused with this behavior. What I might be doing wrong?

My code:

.container {
  height: 500px;
  max-height: 500px;
  display: grid;
  grid-template-columns: 50% 50%;
}

.container .div1 {
  height: 100%;
}

.container .div1 img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="container">
  <div class="div1">
    <img src="https://via.placeholder.com/800" />
  </div>
  
  <div>
    <h1>heading</h1>
  </div>
</div>

2 Answers

I don't fully understand why div1 takes on the height of the img (this can be tested by setting a background color on div1 and setting opacity 0 on the img), but the img itself is overflowing in some sense. Is the combination of grid, 100% height and cover confused in some way.

For now a partial way forward may be to not allow them to overflow. This snippet sets overflow hidden on div1.

.container {
  height: 500px;
  max-height: 500px;
  display: grid;
  grid-template-columns: 50% 50%;
}

.container .div1 {
  height: 100%;
  overflow: hidden;
}

.container .div1 img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="container">
  <div class="div1">
    <img src="https://via.placeholder.com/800" />
  </div>
  
  <div>
    <h1>heading</h1>
  </div>
</div>

This snippet puts a background color on the container and changes the object-fit to contain, just to demonstrate that the object fit and overflow hidden are being invoked.

.container {
  height: 500px;
  max-height: 500px;
  display: grid;
  grid-template-columns: 50% 50%;
}

.container .div1 {
  height: 100%;
  overflow: hidden;
}

.container .div1 img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
.container {
  background: pink;
}
<div class="container">
  <div class="div1">
    <img src="https://via.placeholder.com/800" />
  </div>
  
  <div>
    <h1>heading</h1>
  </div>
</div>

Why don't you use display flex? width: 100%; height: 50%; and if it doesn't work then you use !important like this width: 100% !important;

Related