我应该使用CSS宽度/高度或HTML cols / rows属性来设置textarea的大小吗?

探讨使用CSS或HTML的cols和rows属性设置textarea尺寸的优缺点,包括语义、可访问性和设计考虑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:Should I size a textarea with CSS width / height or HTML cols / rows attributes?

Every time I develop a new form that includes a textarea I have the following dilemma when I need to specify its dimensions: 每当我开发一个包含textarea的新表单时,我都需要指定其维度时遇到以下困境:

Use CSS or use the textarea 's attributes cols and rows ? 使用CSS还是使用textarea的属性colsrows

What are the pros and cons of each method? 每种方法的优缺点是什么?

What are the semantics of using these attributes? 使用这些属性的语义是什么?

How is it usually done? 通常怎么做?


#1楼

参考:https://stackoom.com/question/glFn/我应该使用CSS宽度-高度或HTML-cols-rows属性来设置textarea的大小吗


#2楼

In HTML set 在HTML集中

<textarea rows="10"></textarea>

In CSS set 在CSS集中

textarea { height: auto; }

This will trigger the browser to set the height of the textarea EXACTLY to the amount of rows plus the paddings around it. 这将触发浏览器将textarea的高度完全设置为行数加上它周围的填充。 Setting the CSS height to an exact amount of pixels leaves arbitrary whitespaces. 将CSS高度设置为精确的像素数会留下任意的空格。


#3楼

CSS CSS


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


HTML HTML


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

#4楼

According to the w3c, cols and rows are both required attributes for textareas. 根据w3c,cols和rows都是textareas的必需属性。 Rows and Cols are the number of characters that are going to fit in the textarea rather than pixels or some other potentially arbitrary value. 行和列是要适应textarea而不是像素或其他可能任意值的字符数。 Go with the rows/cols. 去行/列。


#5楼

I recommend to use both. 我建议同时使用两者。 Rows and cols are required and useful if the client does not support CSS. 如果客户端不支持CSS,则行和列是必需且有用的。 But as a designer I overwrite them to get exactly the size I wish. 但作为设计师,我会覆盖它们以获得我想要的尺寸。

The recommended way to do it is via an external stylesheet eg 建议的方法是通过外部样式表,例如

 textarea { width: 300px; height: 150px; } 
 <textarea> </textarea> 


#6楼

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. 没有行和列(即使您没有显式使用它们也有默认值)如果CSS被禁用或被用户样式表覆盖,则textarea会非常小。 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). 话虽如此,如果你的样式表被允许控制textarea的外观,你通常会得到一些看起来更好的东西,适合整个页面设计, 并且可以调整大小以跟上用户输入(当然,在良好的品味范围内)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值