Display a div width 100% with margins

Random78952 picture Random78952 · Nov 10, 2012 · Viewed 61.3k times · Source

I want to display an expandable div (width: 100%) with margins...

Here is my code :

<div id="page">
    <div id="margin">
        "some content here"
    </div>
</div>​

And here is my css code :

#page {
  background: red;
  float: left;
  width: 100%;
  height: 300px;
}

#margin {
  background: green;
  float: left;
  width: 100%;
  height: 300px;
  margin: 10px;
}​

LIVE DEMO

Answer

Vukašin Manojlović picture Vukašin Manojlović · Nov 10, 2012

You can use calc() css function (browser support).

#page {
  background: red;
  float: left;
  width: 100%;
  height: 300px;
}

#margin {
  background: green;
  float: left;
  width: -moz-calc(100% - 10px);
  width: -webkit-calc(100% - 10px);
  width: -o-calc(100% - 10px);
  width: calc(100% - 10px);
  height: 300px;
  margin: 10px;
}​

Alternatively, try using padding instead of margin and box-sizing: border-box (browser support):

#page {
    background: red;
    width: 100%;
    height: 300px;
    padding: 10px;
}

#margin {
    box-sizing: border-box;
    background: green;
    width: 100%;
    height: 300px;
}