[英]Middle (vertically) align text inside a <textarea>
I have a multi-line search box, and I want everything aligned in the middle.我有一个多行搜索框,我希望所有内容都在中间对齐。 Is it possible to vertically center the content of a <textarea>
?是否可以将<textarea>
的内容垂直居中?
You can fake it with vertical padding.您可以使用垂直填充来伪造它。
textarea {
padding: 30px 0;
}
Generally you could use the line-height
property, but you can not with more than one line of text.通常,您可以使用line-height
属性,但不能使用多于一行的文本。
There is the HTML5 contenteditable
attribute.有 HTML5 contenteditable
属性。http://www.w3schools.com/tags/att_global_contenteditable.asphttp://www.w3schools.com/tags/att_global_contenteditable.asp
Maybe the div
tag instead of textarea
can solve your problem.也许div
标签而不是textarea
可以解决您的问题。
Back in the days when i was asking this, i tried achieving this with textarea which is really not possible without scripting.回到我问这个问题的日子里,我尝试使用 textarea 实现这一点,这在没有脚本的情况下是不可能的。 The answer was adding HTML5's contenteditable="true" on a table cell with style="vertical-align: middle".答案是在 style="vertical-align: middle" 的表格单元格上添加 HTML5 的 contenteditable="true"。 If one's project allows modern HTML, this is a rather simple and effective solution.如果一个项目允许使用现代 HTML,这是一个相当简单有效的解决方案。
If instead of adding <table>
and <tr>
and <td>
to your markup, you would like something regular like a <div>
, you would still need two of them:如果不是将<table>
和<tr>
和<td>
到您的标记中,而是想要像<div>
这样的常规内容,您仍然需要其中两个:
<div style="display: table">
<div
style="display: table-cell; vertical-align: middle"
contenteditable="true">
I am vertically aligned
</div>
</div>
You might be able to make a script that determines the elements height, line height, and lines of text and calculate a padding-top, or even \\n to prepend the text.您也许能够制作一个脚本来确定元素高度、行高和文本行数,并计算 padding-top,甚至 \\n 以添加文本。
I do not think this is possible with just CSS though.不过,我认为仅使用 CSS 是不可能的。
not a solution but a workaround, wrap it in a label
and set the position of the textarea to the middle.不是解决方案而是解决方法,将其包装在label
并将 textarea 的位置设置为中间。 caveat: must recalculate the textarea rows once the text content reaches its limit.警告:一旦文本内容达到其限制,必须重新计算 textarea 行。
fiddle: https://jsfiddle.net/syjfoqzx/小提琴: https : //jsfiddle.net/syjfoqzx/
You cannot vertically center the content of a <textarea>
.您不能将<textarea>
的内容垂直居中。 Instead, use a <div>
with content editing enabled.相反,请使用启用了内容编辑的<div>
。 Then use Flexbox layout to center the text.然后使用 Flexbox 布局使文本居中。
[contenteditable] { /* Use Flexbox to center the content */ display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; /* Apply min height of 4 lines */ line-height: 1.2; min-height: calc(1.2em * 4); /* Border styles */ border: 1px solid gray; border-radius: 5px; }
<div contenteditable="true">This text is editable.<br>Go ahead and change it.</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.