====== CSS - Height - DIV 100% height with padding/margin ====== If the parent element is 200px tall and the height is specify as 100% with padding 5px, it would be expected to get a 190px high element with border = 5px on all sides, nicely centered in the parent element. The obvious answer does not work: #myDiv { width: 100% height: 100%; padding: 5px; } ---- ===== Solution ===== **display:block** is the default display value for a div, but **display:explicit** is also good. The container has to be the right type; position attribute is fixed, relative, or absolute. .stretchedToMargin { display: block; position:absolute; height:auto; bottom:0; top:0; left:0; right:0; margin-top:20px; margin-bottom:20px; margin-right:80px; margin-left:80px; background-color: green; }
Hello, world
---- Can also do percentage: *.stretchedMargin { display: block; position:absolute; height:auto; bottom:0; top:0; left:0; right:0; margin-top:1%; margin-right:50%; margin-left:5%; background-color: green; } ---- **NOTE:** This may not work with some older versions of i.e. See the following to fix this: https://code.google.com/archive/p/ie7-js/ ---- ===== Using CSS box-sizing ===== There is a new property in CSS3 that you can use to change the way the box model calculates width/height, it's called box-sizing. By setting this property with the value **border-box** it makes whichever element you apply it to not stretch when you add a padding or border. If you define something with 100px width, and 10px padding, it will still be 100px wide. box-sizing: border-box; See: http://caniuse.com/#feat=css3-boxsizing ---- ===== Using basic CSS ===== The solution is to NOT use height and width at all! Attach the inner box using top, left, right, bottom and then add margin. .box { margin:8px; position:absolute; top:0; left:0; right:0; bottom:0}
This will show three nested boxes. Try resizing browser to see they remain nested properly.
---- ===== Using Calc ===== #myDiv { width: calc(100% - 5px); height: calc(100% - 5px); padding: 5px; } **NOTE:** Do not forget the space between the values and the operator (e.g. (100%-5px) that will break the syntax. See: https://caniuse.com/#feat=calc ----