每次我开发一个包含文本区域的新表单时,当我需要指定它的尺寸时,我都有以下困境:

使用CSS或使用文本区域的属性cols和行?

每种方法的优缺点是什么?

使用这些属性的语义是什么?

通常是怎么做的?


当前回答

文本区域的一个主要特征是它们是可扩展的。在网页上,如果文本长度超过了你设置的空间(无论是使用行还是使用CSS),就会导致文本区域出现滚动条。这可能是一个问题,当用户决定打印,特别是“打印”到PDF -所以设置一个舒适的大最小高度打印文本区域的CSS条件规则:

@media print { 
textarea {
min-height: 900px;  
}
}

其他回答

是的!…总是使用CSS样式文本区域,避免属性,除非你需要支持一些非常老的代理,不支持样式表。否则,您完全可以使用CSS。下面是我默认的CSS文本区格式,在任何网站看起来都很漂亮。根据您的喜好定制它。下面包含了注释,所以你可以看到为什么我选择这些CSS属性和值:

textarea {
    display: inline-block;
    margin: 0;
    padding: .2em;
    width: auto;
    min-width: 30em;
    /* The max-width "100%" value fixes a weird issue where width is too wide by default and extends beyond 100% of the parent in some agents. */
    max-width: 100%;
    /* Height "auto" will allow the text area to expand vertically in size with a horizontal scrollbar if pre-existing content is added to the box before rendering. Remove this if you want a pre-set height. Use "em" to match the font size set in the website. */
    height: auto;
    /* Use "em" to define the height based on the text size set in your website and the text rows in the box, not a static pixel value. */
    min-height: 10em;
    /* Do not use "border" in textareas unless you want to remove the 3D box most browsers assign and flatten the box design. */
    /*border: 1px solid black;*/
    cursor: text;
    /* Some textareas have a light gray background by default anyway. */
    background-color: #eee;
    /* Overflow "auto" allows the box to start with no scrollbars but add them as content fills the box. */
    overflow: auto;
    /* Resize creates a tab in the lower right corner of textarea for most modern browsers and allows users to resize the box manually. Note: Resize isn't supported by most older agents and IE. */
    resize: both;
}

在我的“reset”元素样式表中,我将这些值默认为“textarea”,这让你所有的文本区域都有一个很好的外观和感觉,当检测到滚动时,一个调整大小的选项卡(非ie浏览器),并修复了尺寸,包括一个高度,允许框根据你为用户放入的现有内容来调整自己的大小,以及一个宽度,不超出它的父容器的限制。

 <textarea style="width:300px; height:150px;" ></textarea>

The answer is "yes". That is, you should use both. Without rows and cols (and there are default values even if you don't use them explicitly) the textarea is unusably small if CSS is disabled or overriden by a user stylesheet. Always keep accessibility concerns in mind. That being said, if your stylesheet is allowed to control the appearance of the textarea, you will generally wind up with something that looks a whole lot better, fits into the overall page design well, and that can resize to keep up with user input (within the limits of good taste, of course).

CSS


input
{
    width: 300px;
    height: 40px;
} 

HTML


<textarea rows="4" cols="50">HELLO</textarea>

文本区域 { 高度: 自动; } <行的文本=“10”></textarea>

这将触发浏览器将textarea的高度EXACTLY设置为行数加上它周围的填充。将CSS高度设置为精确的像素数量会留下任意的空白。