【问题标题】:Set parent's (undefined width and height) dimension equal to child's设置父母的(未定义的宽度和高度)尺寸等于孩子的
【发布时间】:2025-09-25 21:45:01
【问题描述】:

我有一个未定义宽度或高度的父 div。

第一个孩子 'a' 已设置宽度和高度。我怎样才能让父母有孩子的尺寸尺寸。

.parent{
    position: fixed;
    background: green;
    padding: 10px;
}

.child-a{
  position:absolute;
  width: 300px;
  height:50px;
  background: red;
}

.child-b{ 
  width:100%;
  height:120%;
  background: blue;
}
<div class='parent'>
  <div class='child-a'></div>
  <div class='child-b'></div>
</div>

第二部分:我希望 div 'c' 是父级高度的 120%,并位于 div 'a' 后面。所以只有 'c' 的底部是可见的。

我尝试了多种解决方案,包括display: tableoverflow: overlay 等,但都没有给我想要的结果。我正在寻找纯 CSS 解决方案

【问题讨论】:

  • 我会在第二部分使用 javascript,它有一个函数来计算父母身高的 120%。如果您愿意,我可以将其发布为答案...
  • Sass variables 适合你吗?使用 calc( parentDimensions ) 您可能会实现您的要求。您能详细说明您要解决的问题吗?

标签: html css css-position


【解决方案1】:
function childSize () {
 var parentHeight = document.getElementById( HAVE PARENTS ID HERE ).offsetHeight;
 parentHeight = parentHeight / 100 * 120;

 document.getElementById( HAVE CHILD C ID HERE ).offsetHeight = parentHeight;
}

此答案仅用于第二部分,希望对您有所帮助:)

【讨论】:

  • 我应该提到我正在寻找纯 CSS 的解决方案。不过还是谢谢。
【解决方案2】:

要使height 百分比起作用,其父级也必须具有高度属性。见https://*.com/a/16642908/5599288。因此,父级的高度不能未定义或自动调整大小。

您必须在父级上设置一个固定高度,然后使用百分比控制子级。我就是这样做的,以纯 CSS 方式,

https://codepen.io/jacobgoh101/pen/jZrvWw

.parent {
  position: fixed;
  background: green;
  padding: 10px;
  width: 300px;
  height: 50px;
}

.child-a {
  position: absolute;
  background: red;
  // set size, padding 10px and centering
  width: calc(100% - 20px);
  height: calc(100% - 20px);
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.child-b {
  width: 100%;
  height: 120%;
  background: blue;
}

【讨论】:

    最近更新 更多