html - CSS 父级意识到堆叠的子级
问题描述
我有两张图像堆叠在一起。我的解决方案有效,我使用绝对位置。
这种方法的缺点是父元素不知道子元素的边界,因此不会使容器适应它。
我怎样才能让父母自动适应这些孩子的大小?
- 接受 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
推荐阅读
- python - 在 Python 中应用函数后如何更改列表内容
- javascript - Apollo 是否缓存突变返回的数据
- python - 如何根据警报从不同 IP 摄像机的 JPEG 快照生成 MJPEG 流
- azure-pipelines - ADF 发布管道上的错误 - 聚合部署错误太大
- angular - 我们如何使用 Angular Material 显示侧边导航栏菜单?
- postgresql - 自定义 PostgreSQL Dockerfile
- r - 在R中的每一行中查找最早和最晚的日期
- html - 如果我设置更大的高度值,为什么我的 flex header 会崩溃?
- powerbi - 如何根据 PowerBI 中的内容提取列
- c# - .NET 标准中的 HttpContextBase 和 System.Web