我正在尝试创建一个简单的 3x3 网格(使用 <table>
),所有单元格都具有 1px
边界。如果我简单地使用 CSS 来提供所有 <td>
元素 a 1px
border 然后内部边框将堆叠并创建 2px
边界所以我对待每个<td>
不同的。我已经成功地做到了这一点并使用了 nth
child 减少CSS。但是,我的问题是为什么使用更少 CSS 选择器的某种逻辑方法不起作用。
这是我的 HTML
<!DOCTYPE html>
<html>
<head>
<title>3x3 grid</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<table>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
</table>
</body>
</html>
这是有效的 CSS:
td{
border: 1px #000;
width:30px;
height: 30px;
text-align: center;
border-style: solid;
}
tr:nth-child(2) td{
border-top: 0px;
}
tr:nth-child(3) td{
border-top: 0px
}
td:nth-child(1){
border-right: 0px;
}
td:nth-child(3){
border-left: 0px;
}
table{
border-spacing: 0px;
border-collapse: separate;
}
这是使用少一个选择器的 CSS,应该可以工作,但不知何故所有上部单元格最终都没有顶部边框。
td{
border: 1px #000;
border-top: 0px;
width:30px;
height: 30px;
text-align: center;
border-style: solid;
}
tr:nth-child(1) td{
border-top: 1px;
}
td:nth-child(1){
border-right: 0px;
}
td:nth-child(3){
border-left: 0px;
}
table{
border-spacing: 0px;
border-collapse: separate;
}
我用 Safari 和 Firefox 测试了它。也请告诉我是否有更好的方法。
最佳答案
td
上没有顶部边框的原因是因为您没有声明border-style
或border-color
...
tr:nth-child(1) td{
border-top: 1px;
}
应该是……
tr:nth-child(1) td{
border-top: 1px solid #000;
}
你可以通过使用 border-collapse: collapse
td{
border: 1px #000;
width:30px;
height: 30px;
text-align: center;
border-style: solid;
}
table{
border-collapse: collapse;
}
<table>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
</table>
关于CSS 嵌套的第 nth-child() 行为很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32906731/