[英]Make child element (with padding) 100% width and height of parent
Is it possible to make a child element (with padding) 100% width and height of its parent element? 是否可以使子元素(带填充)的父元素的宽度和高度为100%?
html: HTML:
<div id="parent">
<div id="child"></child>
</div>
css: 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. 我已经尝试让孩子100%宽度/高度,但由于填充,这使得孩子比父母大。
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. 我还尝试将子位置设为绝对位置,并将顶部,底部,左侧和右侧设置为0,这适用于宽度但不适用于高度。
The parent can be a variable size. 父级可以是可变大小。
In addition needs to work on IE8. 另外需要在IE8上工作。
You need to use the box-sizing: border-box;
你需要使用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. 您可以使用box-sizing
属性。 like this : 像这样 :
#child{
box-sizing:border-box;
padding:15px;
width:100%;
height:100%;
}
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%;
此属性包括填充(和边框,如果你有一些)到孩子的总宽度,所以即使你设置width:100%;
,它也不会溢出容器width:100%;
and give it some padding. 并给它一些填充。
More info about this property on MDN 有关此房产的更多信息在MDN
This property is supported by IE8+ but you will need the -moz-
prefix to support FF28- see canIuse for more info. IE8 +支持此属性,但您需要-moz-
前缀来支持FF28-有关详细信息,请参阅canIuse 。
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. 如果可以使用百分比填充,则可以执行此计算,以使子元素与没有box-sizing
属性的父元素具有相同的大小。
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%;
}
Try changing the box model to use box-sizing: border-box;
尝试更改框模型以使用box-sizing: border-box;
* {
box-sizing: border-box;
}
You may need to use http://modernizr.com/ for support with IE8. 您可能需要使用http://modernizr.com/来获取IE8的支持。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.