Display a div width 100% with margins

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

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

#margin {
  background: green;
  float: left;
  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;
}

Sometimes it's better to do the opposite and give the parent div padding instead:

LIVE DEMO

What I did was change the CSS of #page to:

#page {
    padding: 3%;
    width: 94%; /* 94% + 3% +3% = 100% */

    /* keep the rest of your css */
    /* ... */
}

Then delete the margin from #margin

Note: this also adds 3% to the top and bottom (so 6% to the height) which makes it a little taller than 300px - so if you need exactly 300px, you could do something like padding:10px 3%; and change the height:280px; to add up to 300px again.


You can use the following CSS to achieve the desired result:

#page {
   background: red;
   overflow: auto;
}

#margin {
   background: green;
   height: 280px;
   margin: 10px
}

The correct way to achieve this by standard is:

#margin {
   background: green;
   height: 280px;
   margin: 10px;
   width: auto;
   display: block;
}

Tags:

Html

Css