Including margin for width and height

I want box width and height to include all of the content, padding, border width, and margin by default. Is there a way to do this? Especially, I want to be able to specify something like width: 100% including everything up to the margin.


Solution 1:

This is a vague question, but I'll answer the best I can.

Margin, by definition, is the area around the outside of your box; meaning there's no way to include margins inside of your div.

If you would like more padding on the inside of your box, but you don't want the box to resize, then use: box-sizing:content-box;
Or if you would like to include padding and the border, use: box-sizing:border-box;

A workable solution that preserves the size of your divs and removes overflow would look something like this:

#parent{
    box-sizing:border-box;
    width:100%;
    height:200px;
    padding:2em;
}
#child{
    box-sizing:border-box;
    width:100%;
    height:100%;
    padding:1em;
}

<div id="parent">
   <div id="child"></div>
</div>

Just place the div you want to give margins to inside of another div that has padding. Thus creating faux margins.

Solution 2:

if your margin is for example 10px you can use

width: calc(100% - 20px);
box-sizing: border-box;

browser support

w3schools.com reference

Solution 3:

Set the CSS box-sizing property to border-box to make width and height include the content, border, and padding. This allows you to set width: 100% and still add padding or border. In other words box-sizing: border-box makes width include everything between the inner edges of the margin. There is no way to include the margin itself in such a way.

.example { box-sizing: border-box; width: 100%; padding: 10px }

Useful references

  • CSS Box Model visualization
  • CSS3 UI: box-sizing property
  • * { box-sizing: border-box } FTW