请原谅我提出这样一个简单的问题,我对HTML和CSS都很陌生。有没有一种简单的方法来居中一个文本框?我想试试使用
textarea{
margin-left: auto;
margin-right: auto;
}
但它(显然?)没有起作用。
边距不会影响文本区域,因为它不是块级元素,但如果您愿意,可以将其显示为块级元素:
textarea {
display: block;
margin-left: auto;
margin-right: auto;
}
默认情况下,文本区域的display
属性是inline
,这就是为什么您可以轻松地将它们并排放置,以及为什么text-align: center
的答案也有效。
您还可以通过将文本区域放在类似于flexbox容器中来使其居中显示,像这样:
<style>
div.justified {
display: flex;
justify-content: center;
}
</style>
<div class="justified">
<textarea>Textarea</textarea>
</div>
将该元素的父元素的 text-align
设置为 center
,如下所示:
HTML:
<div>
<textarea></textarea>
<div>
CSS:
div { text-align: center; }
这里有一个例子:http://jsfiddle.net/ujzLt/
text-align:center;
添加到您当前 <div>
的 css 声明中即可。 :-) - Sean Vieira将display: block;
添加到您的文本框样式中。
<!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>
text-align:center;
居中对齐。这应该可以解决问题。在2020年,它对我有效:
textarea {
margin: auto;
display: block;
}