Html 如何制作适合当前视口宽度的 <textarea>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39068128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:43:43  来源:igfitidea点击:

How can I make a <textarea> that fits within the width of the current viewport?

htmlcssresponsive-designtextarea

提问by SebastianHannes

How can I make it so that my <textarea>doesn't go over the border of small displays? I want that my <textarea>gets the width of the current display.

我怎样才能使它<textarea>不超过小显示器的边界?我希望我<textarea>得到当前显示的宽度。

<textarea></textarea>

回答by Abensur

You need to change its default box-sizingto a different value.

您需要将其默认box-sizing值更改为不同的值。

textarea {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;

    width: 100%;
}

回答by Bram Vanroy

Set a max-width on the element.

在元素上设置最大宽度。

textarea {
  max-width: 100%;
}
<textarea></textarea>

回答by cssBlaster21895

Try textarea {max-width:95%;}- it will always fit your display.

尝试textarea {max-width:95%;}- 它始终适合您的显示器。

回答by Hamonbatra

you can disable text area resize by:

您可以通过以下方式禁用文本区域调整大小:

textarea {
   resize: none;
}

and set max-width to the width of the container div or table

并将 max-width 设置为容器 div 或 table 的宽度

回答by user1946891

I agree with all of the above answers but one issue not addressed is that if you don't specify the number of columns the textarea will not actually fill the width of the div or element. So I use the following:

我同意上述所有答案,但有一个未解决的问题是,如果您不指定列数,则 textarea 实际上不会填充 div 或元素的宽度。所以我使用以下内容:

<textarea cols="120" style="max-width:100%;">TEXT GOES HERE</textarea>

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.

我将列数设置为略大于大屏幕上 div 的宽度,随着屏幕变小,它会响应屏幕尺寸。

回答by codejockie

You can do the following:

您可以执行以下操作:

div textarea {
  box-sizing: border-box;
  max-width: 50%;
}
<div>
  <textarea cols="100" rows="7"></textarea>
</div>

Setting both max-widthand box-sizingensures the textarearespects its defined width even when the number of colsexceeds the set max-width.

设置max-widthbox-sizing确保textarea即使数量cols超过 set也遵守其定义的宽度max-width