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

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

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

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

通常是怎么做的?


当前回答

是的!…总是使用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浏览器),并修复了尺寸,包括一个高度,允许框根据你为用户放入的现有内容来调整自己的大小,以及一个宽度,不超出它的父容器的限制。

其他回答

根据w3c, cols和rows都是textarea的必需属性。行和Cols是将适合文本区域的字符数,而不是像素或其他潜在的任意值。顺着row /cols走。

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).

文本区域的大小可以通过cols和rows属性指定,甚至更好;通过CSS的高度和宽度属性。 所有主流浏览器都支持cols属性。 一个主要的区别是<TEXTAREA…>是一个容器标记:它有一个开始标记()。

如果你不是每次都使用line-height:'..';属性控制textarea的高度,width属性控制textarea的宽度。

或者你可以通过下面的css来使用font-size:

#sbr {
  font-size: 16px;
  line-height:1.4;
  width:100%;
}

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

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