首页 > 解决方案 > 让孩子用填充填充 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>

标签: htmlcss

解决方案


如果相对于父级绝对定位,则子级将被放置在其父级的填充之外。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>


一个解释:

绝对定位模型中,一个盒子相对于它的包含块显式地偏移。

绝对定位@w3

如果 position 属性是static 或 relative,则包含块由最近的祖先元素的内容框的边缘形成,该祖先元素是块容器...

如果 position 属性是absolute,则包含块由最近的祖先元素的填充框的边缘形成,该元素的位置值不是静态的(固定的、绝对的、相对的或粘性的)。

识别包含块@moz

我添加了强调和粗体。

进一步参考:盒子模型


推荐阅读