我有一个包含一堆绝对定位控件的 div
。这些控件是动态生成的,我想让 div
扩展以覆盖宽度和高度上的所有内容。如何在 CSS 中实现此目标?
我有一个包含一堆绝对定位控件的 div
。这些控件是动态生成的,我想让 div
扩展以覆盖宽度和高度上的所有内容。如何在 CSS 中实现此目标?
这是通过CSS 网格布局实现的:
.container {
display: grid;
}
.container > * {
grid-area: 1/1;
}
.child {
/* Instead of using top/left, use margins: */
margin-top: 10px;
margin-left: 50px;
}
这将创建一个仅有一个单元格的网格,每个子元素都放在该单元格中。
一个子元素的布局不会影响其他子元素,它们只是彼此重叠,但网格(.container
) 会扩展以适应所有子元素的范围。
这是很难实现的。当您在相对父元素内有绝对子元素时,它们无法影响父div的大小。
您必须也使用相对子元素。为什么控件要定位为绝对位置?
但是,在CSS失败的情况下,JavaScript会挺身而出解决问题。因此,这个问题可以得到解决。
https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio
这里有一个 CodePen,我在其中使用了这种方法: https://codepen.io/cssguru/pen/yLoKYzR?editors=1100
<div class="img-swap">
<img src="https://via.placeholder.com/400x300/fff" />
<img src="https://via.placeholder.com/400x300/fff" />
</div>
html, body {
margin: 0;
padding: 1rem;
}
.img-swap {
position: relative;
aspect-ratio: 4 / 3;
background: red;
$pos-x: 10%;
$pos-y: 10%;
img {
position: absolute;
border-radius: .25rem;
box-shadow: 0 10px 20px rgba(0,0,0,0.1), 0 3px 3px rgba(0,0,0,0.15);
animation-duration: 14s;
animation-iteration-count: infinite;
animation-timing-function: linear;
animation-name: imgSwap;
z-index: 1;
bottom: $pos-y;
right: $pos-x;
width: calc(100% - #{$pos-x});
}
img + img {
animation-name: imgSwap;
animation-delay: 7s;
top: $pos-y;
left: $pos-x;
z-index: 2;
}
@keyframes imgSwap {
0% { opacity: 0; top: 0; left: 0; z-index: 1; }
2% { opacity: 1; top: 0; left: 0; z-index: 1; }
45% { opacity: 1; top: 0; left: 0; z-index: 1; }
55% { opacity: 1; top: $pos-y; left: $pos-x; z-index: 2; }
98% { opacity: 1; top: $pos-y; left: $pos-x; z-index: 2; }
100% { opacity: 0; top: $pos-y; left: $pos-x; z-index: 2; }
}
}
如果我理解正确,你可以这样写:
.parent{
position:relative;
width:100px;
height:100px;
}
.dynamicDiv{
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
}