当我在父母身上添加亲戚时,无法增加孩子的身高
我想将一个高度
添加到儿童div
,但是当我添加位置:相对
向父母添加时,它就不起作用。
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.parent-box {
position: relative;
background-color: red;
width: 100%;
height: 100%;
padding: 2rem;
top: 0;
left: 0;
}
.child-box {
position: absolute;
width: 100%;
height: 100%;
background-color: green;
top: 0;
left: 0;
}
<div class="parent-box">
<div class="child-box">
<h4>child box</h4>
</div>
</div>
I want to add a height
to child div
but when I add position: relative
to parent then it doesn't work.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.parent-box {
position: relative;
background-color: red;
width: 100%;
height: 100%;
padding: 2rem;
top: 0;
left: 0;
}
.child-box {
position: absolute;
width: 100%;
height: 100%;
background-color: green;
top: 0;
left: 0;
}
<div class="parent-box">
<div class="child-box">
<h4>child box</h4>
</div>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要将根部元素和身体设置为100%的高度。
解释:
您的父盒的高度为100%,即父母的全高 - 身体。您没有设置身体的高度,其初始高度是自动的。因此,您的身高是自动的,只占用适合内容和填充所需的空间。
这是一个改进的解决方案,代码较少:
宽度100%是块元素默认的,插图可用于儿童div而不是高度和顶部/左/左,顶部和左侧,上下没有对相对位置元素的影响。
You need to set your root element and body to take up 100% of the height.
Explanation:
Your parent box had a height of 100%, that is the full height of its parent - the body. You hadn't set a height on the body, and its initial height is auto. Therefore your height was auto, only taking up the space needed to fit the content and padding.
Here is an improved solution with less code:
Width 100% is default for block elements, inset can be used for the child div instead of height and top/left, top and left have no effect on relative positioned elements so remove them from the parent.