Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textarea width does not align with the containing div

Tags:

html

css

xhtml

i am wondering why the textarea refuses to stay aligned with the containing div?

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

It is causing me difficulty in ensuring alignment of elements

alt text

like image 219
meow Avatar asked Dec 10 '10 03:12

meow


1 Answers

By default, a <textarea> element is rendered with a border around it. The problem with this is that when you set the width property on an element, you're only setting the content width, not the total width. The total width of the element is (width + border + padding + margin) so when you set the width on the <textarea> to be 100% it sets the content width to 300px but the total width is that 300px plus the default borders, which causes it to exceed the 300px width of the <div>.

You'll could accommodate these borders in the <div> using padding/margins, but a better solution would be to set the box-sizing property on the <textarea> to border-box to force the width property to define the total width of everything up to and including the border of the element.

You'll need to do a bit of research on that property because it's 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 you to look through.

The box-sizing fix works for Firefox, but I haven't tested it in other browsers. It's possible that some of them, particularly when in quirks/legacy mode, could also apply a margin to the element. If this is the case, then all you would need to do would be to remove the margins with CSS (AFAIK, there isn't a widely supported option for box-sizing that extends to margins - only ones for content, padding, and border).

I'd suggest being specific with this fix, and only removing the left/right margins (i.e. margin-left: 0; margin-right: 0;) rather than removing margins entirely (i.e. margin: 0;) to preserve any top/bottom margins if they exist (and if you want to keep them). I know Firefox applies a 1px margin to the top/bottom, and other browsers might as well.

like image 103
AgentConundrum Avatar answered Sep 18 '22 12:09

AgentConundrum