User Tools

Site Tools


css:div_100_height_with_padding_margin

This is an old revision of the document!


CSS - DIV 100% height with padding/margin

If my parent element is 200px tall and I specify height = 100% with padding = 5px I would expect that I should get a 190px high element with border = 5px on all sides, nicely centered in the parent element.

The obvious answer doesn't work:

#myDiv {
    width: 100%
    height: 100%;
    padding: 5px;
}

Answer

display:block is the default display value for a div, but I like to make it explicit.

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;
}
<div class="stretchedToMargin">
  Hello, world
</div>

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;

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}

<code html>

<div class="box" style="background:green">
  <div class="box" style="background:lightblue">
    This will show three nested boxes. Try resizing browser to see they remain nested properly.
  </div>
</div>

</html>

css/div_100_height_with_padding_margin.1589964733.txt.gz · Last modified: 2020/07/15 09:30 (external edit)

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki