5

When assigning some HTML elements (like a form input) 100% width - you can no longer apply any additional styles that might effect the width. Things like border or padding will cause the element to exceed 100%. This results in awkward elements that may be outside of their parent elements.

Since CSS doesn't support width: 100% - 2px; The only way I know around this is to use an absolute pixel width (width: 98px) or chop the element off at 100% which is not really an option.

<div style="overflow:hidden;">
<input style="width:100%; border: 1px solid #000;" />
</div>

Are they're any other ways around this?

Xeoncross
  • 55,620
  • 80
  • 262
  • 364

3 Answers3

9

Along with adding another div, the solution will soon be to use CSS 3 to add the box-sizing attribute to the CSS rules. This new CSS 3 value already works in IE 8 and all other browsers - so if you don't mind skipping IE 6 & 7 you can use it now!

textarea {
        -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
        -moz-box-sizing: border-box;    /* Firefox, other Gecko */
        box-sizing: border-box;         /* Opera/IE 8+ */
}
Community
  • 1
  • 1
Xeoncross
  • 55,620
  • 80
  • 262
  • 364
  • It's funny that all of us copy-paste this css snippet from the same site every time we need it :P – Loupax May 01 '13 at 11:20
4

You can make a container that's 100% without chrome (borders, padding), and then place a block element within, with whatever chrome you want - a block element will fill-up the total width by default.

<style>
.container {width:100%;border:0:margin:0;}
.thingy {border:1px solid black;margin:2px;background:#ddd;}
</style>

<div class="container">
  <div class="thingy">
    Both worlds?
  </div>
</div>
Rudu
  • 15,682
  • 4
  • 47
  • 63
  • It seems this only works on div elements. However, http://stackoverflow.com/questions/271067/how-can-i-make-a-textarea-100-width-without-overflowing-when-padding-is-present/272632#272632 shows a way of adding another div around the element and applying the styling to it. – Xeoncross Jan 11 '11 at 03:01
  • Well, the internal element has to be a block level element (not `inline`, or `inline-block`). – Rudu Jan 11 '11 at 03:05
  • 3
    +1 what I would have said if I was quick enough. :) May also be worth noting that CSS3 gives us `box-sizing: content-box`, which subtracts borders and padding from the calculated width. – Richard Poole Jan 11 '11 at 03:06
  • Ooo, a preview of the future... hooray for the death of the `add extra divs` solution :) Thanks @RP – Rudu Jan 11 '11 at 03:08
0

This is an old question, but it's worth mentioning that since CSS3, you can use calc:

width: calc(100% - 2px);
ki9
  • 5,183
  • 5
  • 37
  • 48