Html 如何使用 CSS 将 textarea 居中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3580063/
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 04:16:30  来源:igfitidea点击:

How to center a textarea using CSS?

htmlcsstextareacenter

提问by Chris

Forgive me for asking such a simple question, I'm new to both HTML and CSS. Is there an easy way to center a textarea? I figured I'd just try using

请原谅我问这么简单的问题,我对 HTML 和 CSS 都是新手。有没有一种简单的方法可以使文本区域居中?我想我只是尝试使用

textarea{
    margin-left: auto;
    margin-right: auto;
}

but it (obviously?) didn't work.

但它(显然?)没有用。

回答by Douglas

The margins won't affect the textarea because it is not a block level element, but you can make it display block if you like:

边距不会影响 textarea 因为它不是块级元素,但是如果您愿意,可以使其显示块:

textarea {
    display: block;
    margin-left: auto;
    margin-right: auto;
}

before and after

之前和之后

By default, textareas are display: inline, which is why you can put them side-by-side easily, and why the text-align: centeranswers work too.

默认情况下, textareas 是display: inline,这就是为什么您可以轻松地将它们并排放置,以及为什么text-align: center答案也有效。

The textarea can also be centered by putting it inside a flexbox containerlike this:

textarea 也可以通过将它放在一个flexbox 容器中来居中,如下所示:

<style>
    div.justified {
        display: flex;
        justify-content: center;
    }
</style>

<div class="justified">
    <textarea>Textarea</textarea>
</div>

回答by davehauser

Set text-alignof the element's parent to center, like this:

text-align元素的父元素设置为center,如下所示:

HTML:

HTML:

<div>
    <textarea></textarea>
<div>

CSS:

CSS:

div { text-align: center; }

Here is an example: http://jsfiddle.net/ujzLt/

这是一个例子:http: //jsfiddle.net/ujzLt/

回答by Jeff Adams

add display: block;to your textarea styles

添加display: block;到您的 textarea 样式

回答by Sotiris

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>#container {width:100%; text-align:center;}</style>
</head>

<body>
<div id="container">
<textarea name="mytextarea" cols="10" rows="10"></textarea>
</div>
</body>
</html>

you wrap your textarea with a div, give it width and then you align it with text-align:center;

你用一个 div 包裹你的 textarea,给它宽度,然后你将它与 text-align:center;