Is it possible to make a child element (with padding) 100% width and height of its parent element?
html:
<div id="parent">
<div id="child"></child>
</div>
css:
#child {
padding: 15px
}
I have tried making the child 100% width/height but this makes the child larger than the parent due to the padding.
I have also tried to make the child position absolute and set top,bottom,left and right to 0 and this works for the width but not the height.
The parent can be a variable size.
In addition needs to work on IE8.
You need to use the box-sizing: border-box;
property:
#child {
padding: 15px
width: 100%;
height: 100%;
box-sizing: border-box;
}
You can use the box-sizing
property for that.
like this :
#child{
box-sizing:border-box;
padding:15px;
width:100%;
height:100%;
}
DEMO
This property includes the padding (and border if you have some) to the total width of the child so it won't overflow the container even if you set width:100%;
and give it some padding.
More info about this property on MDN
This property is supported by IE8+ but you will need the -moz-
prefix to support FF28- see canIuse for more info.
If you can use percent padding, you can do this calculation so the child element has the same size as the parent without the box-sizing
property.
Calculation for the width :
width of child + left and right padding child = 100%
Calculation for the height :
height of child + top and bottom padding child = 100%
example :
#child {
padding: 5%;
width:90%;
height:90%;
}
DEMO
Try changing the box model to use box-sizing: border-box;
* {
box-sizing: border-box;
}
You may need to use http://modernizr.com/ for support with IE8.
Compatibility Table for box-sizing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With