Search code examples
htmlcsscss-positionstacked

CSS parent aware of stacked children


I have two images stacked on top of eachother. My solution works and I use position absolute.

The downside of this approach is that the parent element is not aware of the children boundaries and does therefor not adapt the container to it.

How can I make the parent automatically adapt its size to these children?

  • Flex and Grid solutions are accepted as well as position absolute solutions.
  • I don't want to use javascript.
  • I don't want to hack in a solution where I need to manually set a height to the container.
  • It's fine if it works with modern browsers (Chrome, Firefox, Opera, Safari and Edge)

I think I've read about a solution a long time ago involving grid, but I'm not sure.

div {
  position: relative;
  background: #eee; /* DOES NOT FILL UP */
}

img {
  position: absolute;
}

img:last-child {
  margin-left: 3rem;
  margin-top: 3rem;
}
<div>
  <img src="http://placekitten.com/200/140">
  <img src="http://placekitten.com/200/139">
</div>

Something below


Solution

  • Use CSS grid like below. The trick is to make both images on the same row/column:

    .box {
      display:grid;
      background: lightblue; 
      /* remove the below if you want full width */
      width:-moz-fit-content; 
      width:fit-content;
    }
    
    img {
      grid-row:1;
      grid-column:1;
    }
    
    img:last-child {
      margin-left: 3rem;
      margin-top: 3rem;
    }
    <div class="box">
      <img src="http://placekitten.com/200/140">
      <img src="http://placekitten.com/200/139">
    </div>
    
    Something below

    Also like below using position:absolute with better support:

    .box {
      display: table; /* remove this if you want full width */
      background: lightblue;
      position: relative;
      z-index: 0;
    }
    
    img:first-child {
      position: absolute;
      z-index: -1;
    }
    
    img:last-child {
      margin-left: 3rem;
      margin-top: 3rem;
      display:block;
    }
    <div class="box">
      <img src="http://placekitten.com/200/140">
      <img src="http://placekitten.com/200/139">
    </div>
    
    Something below

    A third solution with negative margin:

    .box {
      display: table; /* remove this if you want full width */
      background: lightblue;
    }
    
    img {
     vertical-align:top;
    }
    
    img:last-child {
      margin-top: 3rem;
      margin-left:-9rem;
    }
    <div class="box">
      <img src="http://placekitten.com/200/140">
      <img src="http://placekitten.com/200/139">
    </div>
    
    Something below