Reputation: 1640
I want to display an expandable div
(width: 100%
) with margins...
#page {
background: red;
float: left;
width: 100%;
height: 300px;
}
#margin {
background: green;
float: left;
width: 100%;
height: 300px;
margin: 10px;
}
<div id="page">
<div id="margin">
"some content here"
</div>
</div>
Upvotes: 80
Views: 94999
Reputation: 2733
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;
}
Upvotes: 105
Reputation: 9
If possible, try to use padding with box-sizing instead, on #page element
#page {
padding: 10px;
box-sizing: border-box;
background: red;
float: left;
width: 100%;
height: 300px;
}
#margin {
background: green;
float: left;
width: 100%;
height: 100%;
}
Upvotes: 0
Reputation: 155
The correct way to achieve this by standard is:
#margin {
background: green;
height: 280px;
margin: 10px;
width: auto;
display: block;
}
Upvotes: 15
Reputation: 92112
For LESS users only:
Using the nice solution of Vukašin Manojlović doesn't work out of the box because LESS executes + or - operations during the LESS compilation. One solution is to escape LESS so that it doesn't execute the operation.
Disable LESS-CSS Overwriting calc()
@someMarginVariable = 15px;
margin: @someMarginVariable;
width: calc(~"100% - "@someMarginVariable*2);
width: -moz-calc(~"100% - "@someMarginVariable*2);
width: -webkit-calc(~"100% - "@someMarginVariable*2);
width: -o-calc(~"100% - "@someMarginVariable*2);
or can use a mixin like:
.fullWidthMinusMarginPaddingMixin(@marginSize,@paddingSize) {
@minusValue: (@marginSize+@paddingSize)*2;
padding: @paddingSize;
margin: @marginSize;
width: calc(~"100% - "@minusValue);
width: -moz-calc(~"100% - "@minusValue);
width: -webkit-calc(~"100% - "@minusValue);
width: -o-calc(~"100% - "@minusValue);
}
Upvotes: 4
Reputation: 1141
Sometimes it's better to do the opposite and give the parent div
padding instead:
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.
Upvotes: 18
Reputation: 853
You can use the following CSS to achieve the desired result:
#page {
background: red;
overflow: auto;
}
#margin {
background: green;
height: 280px;
margin: 10px
}
Upvotes: 11