扩展div以包含绝对定位的内容。

8

我有一个包含一堆绝对定位控件的 div。这些控件是动态生成的,我想让 div 扩展以覆盖宽度和高度上的所有内容。如何在 CSS 中实现此目标?

4个回答

10

这是通过CSS 网格布局实现的:

.container {
  display: grid;
}

.container > * {
  grid-area: 1/1;
}

.child {
  /* Instead of using top/left, use margins: */
  margin-top: 10px;
  margin-left: 50px;
}

这将创建一个仅有一个单元格的网格,每个子元素都放在该单元格中。

一个子元素的布局不会影响其他子元素,它们只是彼此重叠,但网格(.container) 会扩展以适应所有子元素的范围。

演示:https://codepen.io/jaffathecake/pen/zWrvZx


这不是问题的答案。该问题包含了一堆绝对定位的控件,而这个解决方案会使它们全部叠在一起。使用此解决方案无法将它们分散开。 - Adam Youngers
1
正如我在答案中所说,您可以使用边距来相对于网格偏移项目,例如 https://codepen.io/jaffathecake/pen/qBPQoyL - JaffaTheCake
1
这太不可思议了! - Jared Christensen

1

这是很难实现的。当您在相对父元素内有绝对子元素时,它们无法影响父div的大小。

您必须也使用相对子元素。为什么控件要定位为绝对位置?

但是,在CSS失败的情况下,JavaScript会挺身而出解决问题。因此,这个问题可以得到解决。


在我的情况下,子元素是绝对定位的,因为我想在画布上方放置一个D3 SVG,其中SVG处理鼠标交互,而画布处理实际渲染。 - PirateApp

0
如果您知道容器的比例并且项目与该比例相对应,您可以使用纵横比来模拟控件的包含...

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; }
  } 
  
}



-4

如果我理解正确,你可以这样写:

.parent{
 position:relative;
 width:100px;
 height:100px;
}
.dynamicDiv{
 position:absolute;
 top:0;
 bottom:0;
 left:0;
 right:0;
}

20
这并没有扩展父元素以包含子元素,它只是将父元素设置为固定大小。 这可能解决了 OP 的问题,但并没有回答这个问题。 - Bennett McElwee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接