首页 > 解决方案 > CSS 父级意识到堆叠的子级

问题描述

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

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

我怎样才能让父母自动适应这些孩子的大小?

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

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

标签: htmlcsscss-positionstacked

解决方案


使用 CSS 网格,如下所示。诀窍是在同一行/列上制作两个图像:

.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


推荐阅读