【问题标题】:CSS parent aware of stacked childrenCSS 父级意识到堆叠的子级
【发布时间】:2020-07-27 10:41:35
【问题描述】:

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

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

如何让父级自动适应这些子级的大小?

  • 接受 Flex 和 Grid 解决方案以及绝对位置解决方案。
  • 我不想使用 javascript。
  • 我不想破解需要手动设置容器高度的解决方案。
  • 如果它适用于现代浏览器(Chrome、Firefox、Opera、Safari 和 Edge)就很好

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

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

【问题讨论】:

  • 对于与给定示例中尺寸(几乎)完全相同的图像,或者只是完全图像尺寸的任意组合,您是否需要此功能?
  • (你只需要两张像这样叠在一起的图像,还是半打,或者 - “无限”?)
  • @CBroe 我的想法是它可能是一个通用的解决方案。对于不同的情况,你们有不同的解决方案吗?

标签: html css css-position stacked


【解决方案1】:

使用如下 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

【讨论】:

  • 不错!乍一看,它似乎按预期工作。我不知道你为什么投了反对票。到目前为止,我给了它一个赞成票。现在我有一个网格解决方案和一个弹性解决方案,所以我需要选择一个作为正确答案。谢谢!
  • @JensTörnell 你还可以等待,我相信会有更多的解决方案 ;)
  • width: max-content; 而不是 Firefox 的 width:fit-content;
  • @JensTörnell 添加了另一个更受支持的想法
  • @JensTörnell 添加了第三种解决方案
【解决方案2】:

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

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

【讨论】:

  • 不错的解决方案!它按预期工作。我喜欢有弹性和网格解决方案可供选择。
猜你喜欢
  • 1970-01-01
  • 2015-08-14
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 2021-08-14
  • 2015-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多