views:

17997

answers:

5

I have the following HTML snippet being rendered.

<div style="display: block;" id="rulesformitem" class="formitem">
    <label for="rules" id="ruleslabel">Rules:</label>
    <textarea cols="2" rows="10" id="rules"/>
</div>

This is my CSS:

textarea
{
    border:1px solid #999999;
    width:100%;
    margin:5px 0;
    padding:3px;
}

Is the problem is that the text area ends up being 8px wider (2px for border + 6px for padding) than the parent. Is there a way to continue to use border and padding but constrain the total size of the textarea to the width of the parent?

+1  A: 

No, you cannot do that with CSS. That is the reason Microsoft initially introduced another, and maybe more practical box model. The box model that eventually won, makes it inpractical to mix percentages and units.

I don't think it is OK with you to express padding and border widths in percentage of the parent too.

buti-oxa
+12  A: 

The answer to many CSS formatting problems seems to be "add another <div>!"

So, in that spirit, have you tried adding a wrapper div to which the border/padding are applied and then putting the 100% width textarea inside of that? Something like (untested):

textarea
{
    width:100%;
}
.textwrapper
{
    border:1px solid #999999;
    margin:5px 0;
    padding:3px;
}

<div style="display: block;" id="rulesformitem" class="formitem">
    <label for="rules" id="ruleslabel">Rules:</label>
    <div class="textwrapper"><textarea cols="2" rows="10" id="rules"/></div>
</div>
Dave Sherohman
I ended up moving away from using % widths. I believe your approach would work just as well though. Thanks!
spoon16
Don't forget to add "." to the textwrapper class.
Chris Porter
@Chris: Thanks and fixed. I'm mildly surprised that it took almost a year and a half for someone to catch that...
Dave Sherohman
How will the textarea's scrollbars look in this case?
Daniel LeCheminant
+5  A: 

If you're not too bothered about the width of the padding, this solution will actually keep the padding in perspective too..

textarea
{
    border:1px solid #999999;
    width:98%;
    margin:5px 0;
    padding:1%;
}

Not perfect, but you'll get some padding and the width adds up to 100% so its all good

qui
+5  A: 
Emanuele Del Grande
Not sure what cross-browser gotchas lurk here, but I liked the approach. +1
HRJ
+2  A: 

You can make use of the box-sizing property, it's supported by all the main standard-compliant browsers and IE8+. You still will need a workaround for IE7 though.

http://www.quirksmode.org/css/box.html

nkm