html - 让孩子用填充填充 100% 的父母
问题描述
我正在尝试div
使用父母宽度和高度的 100%(包括填充)来制作孩子。无论我尝试什么都行不通。我试图添加box-sizing = border-box
,但这并没有改变任何东西。我还尝试将 box-sizing 添加到使用的所有元素中,*
但这也没有改变任何东西。这是我的代码:
html {
font-size: 16px;
}
.parent {
font-size: 1rem;
width: 10em;
height: 10em;
padding: 5em;
background-color: #f0f0f0;
}
.child {
background-color: #ccc;
width: 100%;
height: 100%;
/*
--= 100% should include padding =--
box-sizing: border-box; <-- this didn't change anything...
*/
}
<div class="parent">
<div class="child"></div>
</div>
解决方案
如果相对于父级绝对定位,则子级将被放置在其父级的填充之外。position:absolute
像这样使用:
.parent {
position: relative;
padding: 2em;
}
.child {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
示范:
html {
font-size: 12px;
}
body {
margin: 1em;
}
.parent {
position: relative;
font-size: 1.2em;
width: 10em;
padding: 2em;
margin:1em 0 0;
background-color: blue;
border: 5px solid red;
}
.child {
position: relative;
background-color: lightgreen;
}
.background {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
p {
margin: 0;
}
.red {
color: red;
}
.blue {
color: blue;
}
.green {
color: green;
}
<p>Parent Border: <span class="red">Red</span></p>
<p>Parent Background: <span class="blue">Blue</span> (not visible)</p>
<p>Child Background: <span class="green">Green</span></p>
<div class="parent">
<div class="child background"></div>
<div class="child">This text to indicate parent's padding</div>
</div>
使用您的代码的工作示例:
html {
font-size: 16px;
}
.parent {
position: relative; /* ADDED */
font-size: 1rem;
width: 10em;
height: 10em;
padding: 5em;
background-color: #f0f0f0;
}
.child {
position: absolute; /* ADDED */
left: 0; /* ADDED */
top :0; /* ADDED */
background-color: #ccc;
width: 100%;
height: 100%;
}
<div class="parent">
<div class="child"></div>
</div>
一个解释:
在绝对定位模型中,一个盒子相对于它的包含块显式地偏移。
如果 position 属性是static 或 relative,则包含块由最近的祖先元素的内容框的边缘形成,该祖先元素是块容器...
如果 position 属性是absolute,则包含块由最近的祖先元素的填充框的边缘形成,该元素的位置值不是静态的(固定的、绝对的、相对的或粘性的)。
我添加了强调和粗体。
进一步参考:盒子模型
推荐阅读
- c# - 创建 RawDiskLibrary 对象时磁盘名称无效
- node.js - “无效的论点”:我错过了什么吗?
- php - 如何在 PHP 的 array_reverse() 函数中使用 echo
- javascript - 如何将此代码转换为一个函数 jquery
- javascript - 在简单的登录表单中单击按 Enter 键
- laravel - 为什么不捕获我在 Laravel 5.7 中定义的路由请求的文件 URI?
- python - 无法从网页解析指向不同海报的链接
- c - c语言中的套接字和线程分段错误
- django - 无法在 Django OneToOneField 模型中访问反向关系
- android-studio - 在 Android 应用中使用 Google 日历的正确方法?