Use a <div>
with negative margins
For any child element, the maximum natural width cannot exceed that of the parent's content width — even if the parent has box-sizing: border-box
defined.
On typical block-level elements and most elements defined with display: block
, you can stretch the child by giving it negative margins equivalent to the padding of the parent container.
This only works if the element has no defined width or it has width: auto
explicitly defined. Defining width: 100%
is insufficient.
For some reason there is no way to accomplish this directly on an input
even if you have defined display: block
(this applies to textarea
and possibly other form elements as well).
I suspect this is because width: auto
defers to the element's default browser-defined width which is calculated uniquely for input
elements.
You can, however nest the input
within a container that has no padding of its own to which you've also applied the negative margins.
Consider the following examples:
* { 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;
}
<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>