我试图让孩子div使用父母宽度和高度的 100%(包括填充)。无论我尝试什么,它都不起作用。我尝试添加,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...
*/
}Run Code Online (Sandbox Code Playgroud)
<div class="parent">
<div class="child"></div>
</div>Run Code Online (Sandbox Code Playgroud)
如果子级相对于父级是绝对定位的,则它将被放置在其父级填充的外部。position:absolute像这样使用:
.parent {
position: relative;
padding: 2em;
}
.child {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
Run Code Online (Sandbox Code Playgroud)
示范:
.parent {
position: relative;
padding: 2em;
}
.child {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
Run Code Online (Sandbox Code Playgroud)
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;
}Run Code Online (Sandbox Code Playgroud)
使用您的代码的工作示例:
<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>Run Code Online (Sandbox Code Playgroud)
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%;
}Run Code Online (Sandbox Code Playgroud)
一个解释:
在绝对定位模型中,盒子相对于其包含块显式偏移。
如果position属性是static或relative ,则包含块由最近的祖先元素的内容框的边缘形成,该祖先元素是块容器...
如果position属性为absolute ,则包含块由位置值不是static(固定、绝对、相对或粘性)的最近祖先元素的填充框的边缘形成。
强调和粗体是我添加的。
进一步参考:盒子模型
在不更改父元素的情况下执行此操作的唯一方法是覆盖父元素的填充。为此,您需要将width和设置height为calc(100% + 10em)。您还需要取消左侧和顶部填充以正确定位元素。将孩子设置为“拥有”并position: relative设置“成为” 。lefttop-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;
}Run Code Online (Sandbox Code Playgroud)
<div class="parent">
<div class="child"></div>
</div>Run Code Online (Sandbox Code Playgroud)