我希望我的整个表格具有“居中”文本对齐,除了某些特定单元格具有“右”文本对齐。在我的代码中,一个单元格被 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>
最佳答案
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>
关于html - CSS 表格文本对齐覆盖特定单元格的文本对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31999987/