Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make child element (with padding) 100% width and height of parent

Tags:

html

css

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.

like image 862
user3416023 Avatar asked May 23 '14 09:05

user3416023


Video Answer


3 Answers

You need to use the box-sizing: border-box; property:

#child {
    padding: 15px
    width: 100%;
    height: 100%;
    box-sizing: border-box;
}
like image 79
sp00m Avatar answered Nov 12 '22 07:11

sp00m


Box sizing property

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.

% padding

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

like image 30
web-tiki Avatar answered Nov 12 '22 07:11

web-tiki


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

like image 36
Paul Redmond Avatar answered Nov 12 '22 08:11

Paul Redmond