Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a div width 100% with margins

Tags:

html

css

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>
like image 803
Random78952 Avatar asked Nov 10 '12 14:11

Random78952


People also ask

How do you make a div 100 width?

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.

Does width 100% include padding?

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.

Is a div 100% width by default?

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.


2 Answers

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; } 
like image 151
Vukašin Manojlović Avatar answered Sep 22 '22 19:09

Vukašin Manojlović


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.

like image 39
Andy Avatar answered Sep 22 '22 19:09

Andy