将父项(未定义的宽度和高度)尺寸设置为等于子项的尺寸



我有一个父级,宽度或高度不确定。

第一个孩子'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仅解决方案

function childSize () {
 var parentHeight = document.getElementById( HAVE PARENTS ID HERE ).offsetHeight;
 parentHeight = parentHeight / 100 * 120;
 document.getElementById( HAVE CHILD C ID HERE ).offsetHeight = parentHeight;
}

这个答案仅是第二部分希望它有帮助的:(

为了使height百分比工作,其父级也必须具有高度属性。请参阅https://stackoverflow.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;
}

相关内容

最新更新