我有两张图片叠在一起。我的解决方案有效,我使用绝对位置。
这种方法的缺点是父元素不知道子元素的边界,因此不会使容器适应它。
如何让父级自动适应这些子级的大小?
- 接受 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/