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.
Without content, the height has no value to calculate the percentage of. The width, however, will take the percentage from the DOM, if no parent is specified.
CSS height and width Values length - Defines the height/width in px, cm, etc. % - Defines the height/width in percent of the containing block. initial - Sets the height/width to its default value. inherit - The height/width will be inherited from its parent value.
Try textarea {max-width:95%;} - it will always fit your display. Show activity on this post. I set the number of columns to slightly greater that the width of the div on a large screen and as the screen gets smaller it acts responsive to the screen size.
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">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With