CSS nested nth-child () acts weird

I am trying to create a simple 3x3 grid (using <table> ) with all cells having a 1px border. If I just use CSS to provide all the <td> elements with a 1px border, then the inner borders will 2px and create a 2px border, so I process each <td> differently. I managed to do it this way and use nth child to reduce CSS. However, my question is that some logical way that uses even fewer CSS selectors does not work.

Here is my 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> 

Here is the CSS that works:

 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; } 

Here is CSS that uses one smaller selector and should work, but somehow all the top cells end up without top borders.

 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; } 

I tested it with both Safari and Firefox. Also, please tell me if there is a better way to do this.

+5
source share
3 answers

The reason you don't have the top border of your td is because you are not declaring border-style or border-color ...

 tr:nth-child(1) td{ border-top: 1px; } 

it should be...

 tr:nth-child(1) td{ border-top: 1px solid #000; } 

This can be simplified simply by using 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> 
+6
source

I donโ€™t know why, but td in the first line changed from solid to none. Try using:

 tr:nth-child(1) td{ border-top: solid black 1px; } 

in CSS and should be right. http://jsfiddle.net/u1d1ctcy/

0
source

You can only do this under the code below:

 <style> table { border-collapse: collapse; } table, td, th { border: 1px solid black; } </style> 
0
source

Source: https://habr.com/ru/post/1232794/


All Articles