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>
What you could do is set your div to be position: absolute so your div is independent of the rest of the layout. Then say width: 100% to have it fill the screen width. Now just use margin-left: 30px (or whatever px you need) and you should be done.
If you set an element's width to 100 pixels, that 100 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width.
auto automatically computes the width such that the total width of the div fits the parent, but setting 100% will force the content alone to 100%, meaning the padding etc. will stick out of the div, making it larger than the parent. so setting the 'width' to 'auto' would be better? Yes, but that's the default anyway.
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; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With