user1187968
user1187968

Reputation: 7986

CSS: 100% width and margin

Please see example at

http://jsfiddle.net/cne94hw4/

.a{
      width: 100%;
    background-color: #eee;
    margin-left: 200px;
}

I was expecting "width 100%" will mean 100% of the windows, but clearly it's not when I add a margin to it. I found this is difficult to understand.

What's the exact relationship of the box and the margin? It's there any written rule for this?

Upvotes: 0

Views: 1977

Answers (3)

Marc Audet
Marc Audet

Reputation: 46785

Your question is about the CSS Box model, which is described in detail at the CSS specification: http://www.w3.org/TR/CSS2/box.html

In brief, the width defines the width of the content box. If you add padding, borders and margins, then the overall width of the block box is the width of the content box plus any widths due to padding, borders and margins.

As for the height, padding and border widths are added to the overall heigth of the block. Margins, though, can collapse with the margins of adjacent blocks, which is another topic to look at (see: collapsing margins).

Another concept is the block formatting context, which comes into play if you deal with elements that may be floated or positioned.

In your example, the overall width of the a element is 100% plus 200px due to the left margin.

Finally, you can have some control over how the width is computed by using the box-sizing property.

Upvotes: 2

Jayant Varshney
Jayant Varshney

Reputation: 1825

try the following

.class{  
   width:100%;
   padding-left:200px;
   box-sizing:border-box;
}

margin adds extra space out of the box.

Upvotes: 0

dramzy
dramzy

Reputation: 1429

width: 100%' does mean100%` of the document your example, but you also set a margin, which is what's limiting the width of the element. See what happens when you remove it.

Upvotes: 0

Related Questions