9
<html>
<head>
<style>
    * { margin:0; border:0; padding:0; }
    div { height:500px; }
    #container { width:1000px; background-color:#000; }
    #column-one { float:left; padding:10px; width:500px; background-color:#234; }
    #column-two { float:left; padding:10px; width:500px; background-color:#345; }
</style>
</head>
<body>
<div id="container">
    <div id="column-one">
    </div>
    <div id="column-two">
    </div>
</div>
</body>
</html>

Counterintuitive indeed.

JJJ
  • 32,902
  • 20
  • 89
  • 102
Sid Bayer
  • 103
  • 1
  • 1
  • 3

3 Answers3

27

The content-box model states that padding and borders don't count in the width that you set for a box. So they add on to its width.

Modern browsers support CSS3's box-sizing: border-box to cause width to represent the total width of content, padding and borders (the default is, of course, content-box, triggering the above behavior).

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • I know this is old, and a topic that is beaten to death, but *why* does the content-box model not include padding? It would be *much* easier to create precise layouts if I could specifically control the size of my divs and still have padding in them. Also, I don't seem to be having any luck in either IE10 or Chrome with the "box-sizing" attribute. Sorry if I sound frustrated. It's not your fault. – Mike U Jun 17 '14 at 14:52
  • @Mike U: That's because content cannot appear in the padding area by definition. Firefox has an experimental `padding-box` value, which is mentioned in the spec but is at-risk and not implemented anywhere else. There must be something else at play if you can't get box-sizing to work on IE10 or Chrome, because as far as I know, they both support it unprefixed. – BoltClock Jun 17 '14 at 15:02
  • I understand *how* the box model works. Mostly just curious *why* it works that way. It seems so unintuitive and illogical. I have gotten the box-model attribute to work since my previous comment. Seems that you can't just apply it to specific classes. Only way I got it to work was to apply it to "*". The classic way just seems illogical. If I want something to be 40% of the screen, and have a padding of 4px, that's impossible to do proper layout with the classic model. just a gripe, I guess. At least I know how to get around it, now. – Mike U Jun 18 '14 at 19:32
  • @MikeU thats why CSS3 isn't the same as CSS2; plus, as we all know, CSS is broken – That Realty Programmer Guy Jan 04 '19 at 21:47
1

Maybe I misunderstood but I think you can solve your problem by using width: auto for the div instead of width: 100%; PS: I know the post is old but maybe still can be useful...

1

The width is the width your content can fill, not the width of the box delimited by your border.

greg0ire
  • 22,714
  • 16
  • 72
  • 101