tags:

views:

5569

answers:

5

I'd like to say that the height of a text area is equal to, say, 50% of the height of the viewport. How can I do that? A simple height: 50% doesn't do the trick.

+1  A: 

I think you need to use javascript in some way to do this. Handle the resize event, and set the text area to be that many pixels.

FryGuy
Thanks man. I just did that in JavaScript, and it works quit well.
Alessandro Vernet
A: 

You can do it if you set display:block. But in html 4.01 strict you must define cols and rows, but I think you can override them with css.

Vasil
+1  A: 

While I do not have all browsers to test this in, it appears as though most accept simply specifying the height should work.

I tested this in Internet Explorer 7, and Firefox 3.0.

Simply use the following code:

<textarea style="height: 50%; width: 80%;">Your text here</textarea>

What browser(s) were you having issues with?

Brian
+1  A: 

HTML and CSS aren't so good at doing this kind of thing with heights. They are definitely more about scrolling vertically through a free-flowing page. I think JavaScript is likely to be your most complete solution, as FryGuy says.

Kevin Conner
+1  A: 

A simple height: 50% doesn't do the trick.

No, because its parent doesn't have an explicit height. So 50% of what? Parent says ‘auto’, which means base it on the height of the child content. Which depends on the height on the parent. Argh! etc.

So you have to give its parent a percentage height. And the parent's parent, all the way up to the root. Example doc:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;&lt;head&gt;
    <style type="text/css">
        html, body { margin: 0; padding: 0; }
        html, body, #mything, #mything textarea { height: 100%; }
    </style>
</head><body>
    <div id="mything">
        <textarea rows="10" cols="40">x</textarea>
    </div>
</body></html>

The other possibility if you don't want to have to set height on everything is to use absolute positioning. This changes the element that dimensions are based on from the direct parent to the nearest ancestor with a ‘position’ setting other than default ‘static’. If there are no ancestor elements with positioning, then dimensions are based on the “Initial Containing Block”, which is the same size as the viewport.

Finally, there's the trivial problem of ‘100%’ being slightly too big because of the additional padding and border applied to textareas. You can work around this by:

  • compromising on something like 95%, or
  • setting padding and border to 0/none on the textarea, or
  • using “box-sizing: border-box;” to change what ‘height’ means. This is a CSS future soup feature which requires many additional browser-specific restatements (such as ‘-moz-box-sizing’).
bobince