如何实现textarea中文本的垂直居中(已实现水平居中)
实现textarea文本的垂直居中(纯CSS方案)
现有如下textarea和CSS代码,已通过text-align: center实现文本水平居中,但希望同时实现垂直居中——无论文本行数多少,文本的中间行始终处于textarea的垂直中点位置,且仅用CSS实现。
现有代码
CSS
#map-title { font-family: Arial, Helvetica, sans-serif; font-weight: bold; flex: 30%; height: 100%; resize: none; border: 0; outline: none; text-align: center; }
HTML
<textarea id="map-title" type="text" name="title" maxlength="50" wrap="hard" cols="25" rows="2">The text-align property has allowed the text to be centred horizontally, but I want it to also be centered vertically so that, regardless of the number of lines of text, the middle line will always be in the middle of the textarea. I suspect I should use padding, but it would need to adjust based on the size and amount of text on the screen, which I'm not sure how to handle (and I would prefer using only CSS if possible).</textarea>
纯CSS解决方案
直接修改#map-title的CSS样式,利用Flex布局即可实现自动垂直+水平居中,无需手动计算padding:
#map-title { font-family: Arial, Helvetica, sans-serif; font-weight: bold; flex: 30%; height: 100%; resize: none; border: 0; outline: none; /* 保留原有水平居中设置 */ text-align: center; /* 添加Flex相关属性实现垂直居中 */ display: flex; align-items: center; /* 确保多行文本整体水平居中 */ justify-content: center; /* 清除浏览器默认内边距,避免干扰居中计算 */ padding: 0; }
方案说明
display: flex将textarea转换为Flex容器,内部文本会作为Flex项目被布局align-items: center让文本在垂直方向上居中对齐,无论文本行数多少都能自动适配justify-content: center配合text-align: center,确保多行文本整体在水平方向保持居中- 移除默认
padding是因为浏览器自带的内边距会破坏居中的精确性
若仅需单行文本垂直居中,也可使用line-height等于textarea高度的方法,但该方案不适用于多行场景,因此更推荐Flex布局方案。
内容的提问来源于stack exchange,提问作者dylan
相关产品推荐
相关产品推荐

