2014-03-25 80 views
0

我想中心一個元素。應該將`text-align:center;`應用於元素還是其父容器?

應該將text-align: center;應用於元素或其父容器?

有鑑於此:

<div class="container"> 
    <h1>This is a centered header.</h1> 
</div> 

...我應該這樣寫:

.container { 
    text-align: center; 
} 

...或這個:

.container h1 { 
    text-align: center; 
} 
+0

答案取決於你正在嘗試做的。 – Arbel

+0

@Arbel我想中心一個元素。 – Rudiger

+0

如果你試圖以'h1'爲中心,那麼'.container h1'就足夠了,但如果你試圖將h1'本身居中,那麼這是一個完全不同的場景,因爲'h1'是一個塊級別元素,並在您的文檔流中的'h1'元素出現時將所有可用寬度提供給塊級元素。 – Arbel

回答

1

雙方將合作。嘗試一下 - 這裏有一個JS小提琴: http://jsfiddle.net/a4jmB/

.container { 
    text-align: center; 
} 

,設置父DIV中的所有文本爲中心。

.container h1 { 
    text-align: center; 
} 

設置h1 div中的所有文本都居中。 基本上,無論css設置如何,h1都會佔用整行寬度,所以文本將居中。

但是,第二個可能更可取,因爲它只適用於h1 div,而不適用於可能在容器中的任何其他文本。

1

要麼將​​工作,如果雙方的佈局讓他們跨越你希望他們在中心的空間如果你的<h1>有例如float:left;應用,增加text-align: center;到容器不會居中元素。在這種情況下,您需要將width:100%; text-align:center;添加到實際的<h1>元素中。

0

它對所有塊元素都可以正常工作,這些塊元素不會通過floatdisplay更改。 在特定情況下,如果.container中有任何其他內容不應居中,這很重要。那麼你應該使用第二個代碼。即使你想擴展你的代碼,它也會讓你感覺到它,因爲它是一個更乾淨的代碼。

0

在CSS的text-align屬性被用於對準塊元件內容。 css-tricks

的< H1>元素是,默認情況下block level element。 因此,它將填充所有可用的寬度,並且通常以新行開始。

<!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> 

由於一些其他的答案已經提到,請注意,應用「文本對齊:中心」時,屬性和值任何元素,所有的子元素將繼承財產「文本對齊」與值中心,除非特別未設置。

W3C Inherited-property Values

例如:

<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> 
相關問題