Textarea width does not align with containing div

I am wondering why the text box refuses to stay consistent with the containing div?

<!-- the textarea pokes out--> <div style="border:1px solid #ccc; width:300px"> <textarea style="width:100%"></textarea> </div> 

It makes me difficult to align the elements.

alt text

+6
html css xhtml
source share
4 answers

By default, the <textarea> element is displayed with a frame around it. The problem is that when you set the width property of an element, you only set the width of the content, not the total width. The total width of the element is (width + border + padding + margin), so when you set the width <textarea> to 100%, it sets the width of the content to 300 pixels, and the total width is 300px plus the default value of the borders, which leads to that it exceeds the width of the <div> 300px.

You can place these borders in the <div> using indentation / margins, but the best solution would be to set the box-sizing property on <textarea> on the border-box to force the width property to determine the total width of everything, down to the border of the element.

You will need to examine this property a bit, because it is declared differently in all browsers (e.g. -moz-box-sizing , -ms-box-sizing , -webkit-box-sizing , etc.). Here is the QuirksMode page on box-sizing for viewing.

The box-sizing fix works for Firefox, but I have not tested it in other browsers. Perhaps some of them, especially in quirks / legacy mode, can also apply margin to an element. If so, then all you have to do is delete the fields using CSS (AFAIK, for box-sizing widespread option is not supported, which applies to fields - only for content, filling and border).

I would advise clarifying this fix and removing only the left / right fields (i.e. margin-left: 0; margin-right: 0; ), and not completely delete the fields (i.e. margin: 0; ) to save any upper and lower fields, if they exist (and if you want to keep them). I know that Firefox applies a 1px token to the top / bottom, and other browsers can too.

+17
source share

I tried this in Firefox, Chrome and IE, and they all show it correctly. I suspect that the DIV is inside another container and that is causing the problem.

Please add some of your code.

0
source share

A text field can have a margin on it. Try the following:

 <div style="border:1px solid #ccc; width:300px"> <textarea style="width:100%; margin: 0;"></textarea> </div> 
0
source share
 <div style="border:1px solid #ccc; width:300px"> <textarea style="width:100%"></textarea> </div> 

Tested work on Firefox 3.6.10, Internet Explorer 8 and Google Chrome.

But perhaps instead of including it in a DIV, you can also try the following:

 <textarea style="border:1px solid #ccc; width:300px"></textarea> 

Which one has the same appearance as the source code.

0
source share

All Articles