2015-08-13 23 views
1

我希望我的整個表具有「中心」文本對齊,除了一些特定的單元格有「正確」的文本對齊。在我的代碼中,一個單元更具體地由CSS定位,但更一般的分配重寫。爲什麼是這個,我該如何解決它?CSS表格的文本對齊覆蓋特定單元格的文本對齊?

.data td { 
 
    text-align: center; 
 
} 
 
.animal { 
 
    text-align: right; 
 
}
<table class="data"> 
 
    <tr> 
 
     <th>Type of Animal</th> 
 
     <th>Favorite Food</th> 
 
    </tr> 
 
    <tr> 
 
     <td class="animal">Cat</td> 
 
     <td>Mouse</td> 
 
    </tr> 
 
</table>

回答

3

CSS選擇器解釋從最到最具體,因此增加你的CSS選擇器的特殊性得到它的工作。

我建議不要使用!important,因爲這會使CSS更難在未來添加/覆蓋。

還有一個helpful MDN article on CSS specificity,它可以幫助您瞭解爲什麼您的CSS不會像您期望的那樣覆蓋其他規則。

.data td { 
 
    text-align: center; 
 
} 
 
.data td.animal { 
 
    text-align: right; 
 
}
<table class="data"> 
 
    <tr> 
 
     <th>Type of Animal</th> 
 
     <th>Favorite Food</th> 
 
    </tr> 
 
    <tr> 
 
     <td class="animal">Cat</td> 
 
     <td>Mouse</td> 
 
    </tr> 
 
</table>

2

的。數據TD將覆蓋。動物,因爲它有更多的控制權做出類似

.data td { 
 
    text-align: center; 
 
} 
 
.data .animal { 
 
    text-align: right ; 
 
}
<table class="data"> 
 
    <tr> 
 
     <th>Type of Animal</th> 
 
     <th>Favorite Food</th> 
 
    </tr> 
 
    <tr> 
 
     <td class="animal">Cat</td> 
 
     <td>Mouse</td> 
 
    </tr> 
 
</table>