Children of padded parents
How to make children fit the full width of a parent block element that has padding.
In response to: http://stackoverflow.com/questions/21746741/how-to-fit-child-div-to-parent-div-when-parent-div-have-padding
by Gerald Fullam
March 09, 2015
HTML
<div class="myuncoolparentdiv">
<div class="mybaddiv">
My Bad Div has width: 100%;
</div>
<h2>Other Content</h2>
</div>
<div class="myuncoolparentdiv">
<div class="mycooldiv">
My Cool Div has no defined width (~ width: auto;)
</div>
<h2>Other Content</h2>
</div>
<div class="myuncoolparentdiv">
<input class="mybadinput" type="text" value="My Bad Input has width: auto;" />
<h2>Other Content</h2>
</div>
<div class="myuncoolparentdiv">
<input class="mybadinputtoo" type="text" value="My Bad Input has width: 100%;" />
<h2>Other Content</h2>
</div>
<div class="myuncoolparentdiv">
<input class="myreluctantinput" type="text" value="My Reluctant Input has position: absolute;" />
<h2>Other Content</h2>
</div>
<div class="myuncoolparentdiv">
<div class="mycoolparentdiv">
<input class="mycoolinput" type="text" value="My Cool Input has width: 100% and a cool parent div" />
</div>
<h2>Other Content</h2>
</div>
CSS
* { box-sizing: border-box } /* FTW */
h2 {
margin: 0;
padding: 0;
line-height: 1;
}
.myuncoolparentdiv {
position: relative;
margin: 10px;
padding: 10px 20px;
background-color:#0099FF;
}
.mycoolparentdiv {
margin: 0 -20px;
}
.mybadinputtoo {
display: block;
width: 100%;
margin: 0 -20px;
}
.myreluctantinput {
display: block;
position: absolute;
width: 100%;
right: 0;
left: 0;
}
.mycoolinput {
width: 100%;
}
.mycooldiv {
margin: 0 -20px;
padding: 3px;
background-color: tomato;
border: 1px solid gold;
}
.mybaddiv {
width: 100%;
margin: 0 -20px;
padding: 3px;
background-color: tomato;
border: 1px solid gold;
}