开发者

The 100% width HTML element problem

When assigning some HTML elements (like a form input) 100% width - you can no longer apply any additional styles that might effect the width.开发者_如何学JAVA 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?


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+ */
}


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>


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

width: calc(100% - 2px);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜