html - CSS parent 知道堆叠的 child

标签 html css css-position stacked

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

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

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

  • 接受 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

最佳答案

像下面这样使用 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

关于html - CSS parent 知道堆叠的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63113634/

相关文章:

html - CSS 应用不正确?

html - 如何删除我的视频播放器上的轮廓

html - z-index 无法在叠加层上方获取元素

html - 将子 div 置于父 div 之上

html - 基于 CSS 的网格错位问题

html - html5中如何控制列中的内容

html - 使用具有可变高度的 Bootstrap div 创建网格

html - 我的内容在标题上方?

css - 创建一个占据 iPad 视口(viewport)的 CSS 布局

css float 及其堆叠顺序