让孩子用填充填充父母的100%

时间:2019-04-11 17:30:42

标签: html css

我正在尝试使用父母宽度和高度的100%(包括填充)来生孩子div。无论我尝试什么,都行不通。我尝试添加box-sizing = border-box,但没有任何改变。我还尝试使用*将框调整大小添加到所有元素,但是也没有任何改变。 这是我的代码:

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>

2 个答案:

答案 0 :(得分:3)

如果相对于父级绝对放置,则子级将放置在其父级填充的外部。 像这样使用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>


说明:

  

绝对定位模型中,一个框相对于其包含块明确地偏移。

Absolute positioning @ w3

  

如果position属性是静态的还是相对的,则包含块是由作为块容器的最近祖先元素的内容框的边缘形成的。

     

如果position属性是 absolute ,则包含块的位置是距离最近的祖先元素的 padding box 的边缘,该元素的位置值不是static(固定,绝对,相对或粘性)。

Identifying the containing block @ moz

我强调并加粗了。

更多参考:box model

答案 1 :(得分:2)

唯一做到这一点而不改变父级的方法是覆盖父级元素的填充。为此,您需要将 Observable.Start( () => UpdateUiThreadCollections(result), RxApp.MainThreadScheduler ); RxApp.MainThreadScheduler.Schedule(() => { UpdateUiThreadCollections(result); }); width设置为height。您还需要取反左侧和顶部填充以正确定位元素。将孩子设为calc(100% + 10em),并将position: relativeleft设为top

-5em
html {
  font-size: 16px;
}

.parent {
  font-size: 1rem;
  width: 10em;
  height: 10em;
  padding: 5em;
  background-color: #f0f0f0;
}

.child {
  background-color: #ccc;
  width: calc(100% + 10em);
  height: calc(100% + 10em);
  position: relative;
  left: -5em;
  top: -5em;
}

相关问题