CSS parent 意识到堆叠 children

CSS parent aware of stacked children

我有两张图片叠在一起。我的解决方案有效,我使用绝对位置。

这种方法的缺点是 parent 元素不知道 children 边界,因此不会使容器适应它。

如何让 parent 自动适应这些 children 的大小?

我想我很久以前就读过一个涉及网格的解决方案,但我不确定。

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

使用 CSS 网格,如下所示。诀窍是让两个图像在同一个 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

也像下面使用 position:absolute 更好的支持:

.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

负边距的第三种解决方案:

.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

您只需使用弹性容器中的边距即可做到这一点,只需根据需要调整边距即可

div {
  position: relative;
  background: #eee; /* DOES NOT FILL UP */
display: flex;
    align-items: flex-start;
}


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

Something below