Html <tr> 中第一个 <td> 的 CSS 样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19192960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS style for first <td> in a <tr>
提问by Gargoyle
I'm trying to set all the <td> elements of my <tr> to be right-aligned except the first one, which I want to be left-aligned. I tried this:
我试图将我的 <tr> 的所有 <td> 元素设置为右对齐,除了第一个我想左对齐的元素。我试过这个:
<style>
td { text-align: right };
td:first-child { text-align: left };
</style>
That makes all cells be right-aligned. If I swap the order of those two rows, then all cells are left-aligned. Highly confused. According to w3schools,
这使得所有单元格都右对齐。如果我交换这两行的顺序,则所有单元格都左对齐。高度混乱。根据 w3schools 的说法,
The :first-child selector is used to select the specified selector, only if it is the first child of its parent.
:first-child 选择器用于选择指定的选择器,仅当它是其父级的第一个子级时。
But that doesn't seem to be happening for me.
但这对我来说似乎不会发生。
回答by Josh Crozier
Your syntax was incorrect.
你的语法不正确。
td { text-align: right }; /* This was being applied */
td:first-child { text-align: left }; /* This wasn't.. */
Should be:
应该:
td { text-align: right; }
td:first-child { text-align: left; }
Note the semi-colons - they shouldn't be outside of the brackets {}
注意分号——它们不应该在括号之外 {}
Other than that, you were using :first-child
properly.
除此之外,你使用:first-child
得当。
回答by Sean Berce
td:nth-child(2) { text-align: right; }
You can do that in one line.
你可以在一行中做到这一点。
回答by TimSPQR
Another option, depending on what you want to do:
另一种选择,取决于你想做什么:
table tr td {
background-color:red;}
table tr td:nth-child(1) {
background-color:green;}