我有一个未定义宽度或高度的父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: table
,overflow: 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;
}