【问题标题】:absolute positioned parent with a flex growing child not inheriting width绝对定位的父级,具有 flex 生长的子级不继承宽度
【发布时间】:2022-02-02 22:05:12
【问题描述】:

我有一个弹性盒子,它会根据里面的内容逐列增长;盒子的宽度应该适合内容。我必须将此框放在绝对定位在页面上的父容器中。

如果这样做,父容器不会采用子容器的动态宽度,而是坚持其初始宽度并且子容器会溢出。

可用代码:https://jsfiddle.net/visu310p/q8hsk42L/8/

.parent {
  color: white;
  background: blue;
  margin: auto;
  padding: 1em;
  position: absolute;
  left: 10px;
  top: 100px;
}
.child {
  background-color: green;
  display: flex;
  height: 100px;
  flex-direction: column;
  flex-wrap: wrap;
  margin: 0;
}

【问题讨论】:

  • 这里的child会有自动宽度,会随着flex的内容而增长,所以我真的不知道它会拉伸多少。

标签: html css flexbox absolute


【解决方案1】:

您必须为父级设置width。这是因为每当一个元素被绝对定位时,widthheight 都会自动设置为 auto。所以在你的情况下,孩子的flex-wrap: wrap 将导致溢出,除非为绝对定位的父母指定width

.parent {
  color: white;
  background: blue;
  margin: auto;
  padding: 1em;
  position: absolute;
  left: 10px;
  top: 100px;
  width: calc(100% - 20px); /* can be any value */
}
.child {
  background-color: green;
  display: flex;
  height: 100px;
  flex-direction: column;
  flex-wrap: wrap;
  margin: 0;
}

【讨论】:

  • 我已经尝试将宽度设置为 100%,但由于某种原因,它超出了子 div 并跨越了页面。也许,我搞砸了父级的“显示”。对于灵活的孩子,父母应该是某种类型吗?
  • “我已经尝试将宽度设置为 100%,但由于某种原因它超出了孩子的范围”。这是因为您将父级从左侧推了 10px (left: 10px)。你可以使用width: calc(100% - 20px) 之类的东西来让它工作。
  • 我的实际用例会略有不同,但是是的,我明白了……谢谢 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-14
  • 2021-12-07
相关资源
最近更新 更多