给定一个文本区,它是一个小框,单行开始,是否可以使用CSS自动增长为多行,因为用户键入多行,直到设置限制(300px),滚动条将出现溢出自动与所有输入?
是的,你可以用CSS3。您可能需要在浏览器中添加这些前缀。
textarea {
resize: both;
} /* none|horizontal|vertical|both */
textarea.vert {
resize: vertical;
}
textarea.noResize {
resize: none;
}
然后,您可以使用以下方法限制它们的最大高度和宽度:
textarea {
resize: vertical;
max-height: 300px;
min-height: 200px;
}
textarea.horiz {
resize: horizontal;
max-width: 400px;
min-width: 200px;
}
我从我过去参考过的一篇文章中摘取了这些:
使用CSS自定义文本区域大小
2020更新-使用ContentEditable
因为这个答案仍然时不时地帮助一些人,我想用Chris Coiyer的最新发现来更新我的答案。
请注意,它仍然不是一个CSS3解决方案。但它是浏览器内置的,并重新创建OP的搜索行为。
在上使用
ContentEditable
HTML属性将允许用户编辑div
的文本内容,并在用户断行时展开。然后,只需将div
转换为。
<div
class="expandable-textarea"
role="textbox"
contenteditable
>
Your default value
</div>
.expandable-textarea {
border: 1px solid #ccc;
font-family: inherit;
font-size: inherit;
padding: 1px 6px;
display: block;
width: 100%;
overflow: hidden;
resize: both;
min-height: 40px;
line-height: 20px;
}
这个解决方案的一个警告是,我们没有使用文本。请记住,一些特性(如占位符)需要使用来实现一些创造性
资料来源:伟大的克里斯·科伊尔。链接到他的博客
原始答案:使用轻量级JS库的解决方案
不幸的是,仅仅使用CSS3似乎无法做到这一点。
但是,有一个3.2K的小型JS可供选择。
这里是包括演示和用法的链接。
您可以通过执行npm install autosize
并使用以下方式安装它
autosize(document.querySelector('.yourTextAreaClass'));
或jQuery样式
autosize($('.yourTextAreaClass'));
它就像一个符咒。它是轻量级的,有一个自然的感觉,不像许多autoresize是做无用的动画。
Chris Coyier(因CodePen而出名)刚刚发布了一个基于网格的CSS实现。来自Chris Coyier的原始代码-2020年10月30日
null
.grow-wrap {
/* easy way to plop the elements on top of each other and have them both sized based on the tallest one's height */
display: grid;
}
.grow-wrap::after {
/* Note the weird space! Needed to preventy jumpy behavior */
content: attr(data-replicated-value) " ";
/* This is how textarea text behaves */
white-space: pre-wrap;
/* Hidden from view, clicks, and screen readers */
visibility: hidden;
}
.grow-wrap>textarea {
/* You could leave this, but after a user resizes, then it ruins the auto sizing */
resize: none;
/* Firefox shows scrollbar on growth, you can hide like this. */
overflow: hidden;
}
.grow-wrap>textarea,
.grow-wrap::after {
/* Identical styling required!! */
border: 1px solid black;
padding: 0.5rem;
font: inherit;
/* Place on top of each other */
grid-area: 1 / 1 / 2 / 2;
}
body {
margin: 2rem;
font: 1rem/1.4 system-ui, sans-serif;
}
label {
display: block;
}
<form action="#0">
<label for="text">Text:</label>
<div class="grow-wrap">
<textarea name="text" id="text" onInput="this.parentNode.dataset.replicatedValue = this.value"></textarea>
</div>
</form>