我想把一个元素居中
应该将text-align: center;
应用于元素还是其父容器?
给定:
<div class="container">
<h1>This is a centered header.</h1>
</div>
…我应该这样写吗?
.container {
text-align: center;
}
…或:
.container h1 {
text-align: center;
}
都可以。试试吧-这是一个JS小提琴:http://jsfiddle.net/a4jmB/
.container {
text-align: center;
}
设置父div中的所有文本居中。
.container h1 {
text-align: center;
}
将h1div中的所有文本设置为居中。基本上,不管css设置如何,h1占据了整个行宽,因此文本将居中。
不过,第二个可能更可取,因为它只适用于h1div,而不适用于容器中可能存在的任何其他文本。如果它们的布局都允许它们跨越你想要它们进入的空间,那么它们都可以工作。例如,如果您的<h1>
已经应用了float:left;
,那么将text-align: center;
添加到容器中将不会使元素居中;在这种情况下,您需要将width:100%; text-align:center;
添加到实际的<h1>
元素中。
对于所有块元素都可以正常工作,这些元素不会通过float
或display
进行更改。在特殊情况下,如果.container
中有任何其他不应该居中的内容,这一点很重要。那么你应该使用第二个代码。即使你想扩展你的代码,它也是有意义的,因为它是一个更干净的代码。
CSS中的text-align属性用于对齐块元素的内部内容。css技巧
& lt;元素在默认情况下是块级元素。因此,它将填充所有可用的宽度,并且通常从新行开始。
<!doctype html>
<html lang="en">
<meta charset="UTF-8">
<head>
<style>
h1 { text-align:center;}
</style>
<head>
<body>
<div class="container">
<h1>This is a centered header.</h1>
</div>
</body>
<html>
正如其他一些答案已经提到的那样,请注意,当对任何元素应用'text-align:center'属性和值时,所有子元素将继承属性"text-align"和值center,除非特别取消设置。
W3C继承属性值
例如:
<style>
.container {text-align:center;}
</style>
<div class="container">
<h1>This is a centered header.</h1>
<h4>All of the other content on your site</h4>
<p>Will be centered, because it falls within the .container </p>
<ul>
<li>Including:</li>
<li>nested elements</li>
</ul>
</div>