I know the CSS spec states that the width property should not include borders and padding, so in the following example...

.foo {
  width: 20px;
  padding: 5px;
  border: 1px solid black;
}

...foo will have a width of 20px and an offset width of 1 + 5 + 20 + 5 + 1 = 32px.

What I would like to do is specify an element's width to be 100% of its parent, plus some padding and borders without it spilling over. In other words, in this example...

.parent {
  width: 100px;
}
.parent .child {
  width: 100%
  padding: 0.2em;
  border: 1px solid black;
}

... I would like child's offset width to be 100px. (This is just an example for clarity's sake, in the real world the parent's width would be arbitrary and mutable.)

My specific use case is in designing a bulletproof form layout engine. I need text inputs to be sized by their containers. The workaround I've used is to wrap the element in a div:

div.input-wrap {
  padding: 0.15em 0.1em;
  border: 1px solid #888;
}
div.input-wrap input[type="text"] {
  width: 100%;
}

This is nice because input-wrap will default to 100% its parent's width, but not nice because of a) the extra element and b) if I want to set a width on the wrapping element, I'm back where I started.

Is there a pure CSS (no extra markup or javascript) way to achieve my goal?

  • Thanks to Richard's answer, I found this great quirksmode article on the different box models: http://www.quirksmode.org/css/box.html Zak Linder almost 7 years ago

2 answers

3
points
This was chosen as the best answer

CSS 3 will (almost certainly) have a property controlling this:

box-sizing: border-box
box-sizing: content-box

Mozilla, Webkit and IE8 are supporting it already via interim properties:

-ms-box-sizing: border-box
-ms-box-sizing: content-box;
-moz-box-sizing: border-box;
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box 
-webkit-box-sizing: border-box

And it appears that Opera 10 is already supporting the non-prefixed version. If you are after border box, given that Older versions of IE use a border-box model anyway, you may well be able to use this solution already.

Answered almost 7 years ago by Richard Grevers
  • Thanks Richard! I think that should do it. In my case I don't have to support IE6 and I'm okay with IE7 users having a slightly wonky experience :P. Zak Linder almost 7 years ago
  • Thanks RichardI didn't know that Microsoft had implemented the box-sizing property! Just to add to this, you can actually get IE 5 and above to support the box-sizing property too, and quite easily at that, using box-sizing.htc. See http://webfx.eae.net/dhtml/boxsizing/boxsizing.html for more information. Jordan Gray almost 7 years ago
0
points

To my knowledge, you are doing the best you can do in that situation. I've run into that problem in the past and ended up doing the same thing you did. Hopefully I'm wrong and someone comes along with a better answer, haha.

Answered almost 7 years ago by Matt Milburn