Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS nested nth-child() is acting weird

I'm trying to create a simple 3x3 grid (using <table>) with all cells having a 1px border. If I simply use CSS to give all <td> elements a 1px border then the inner borders will stack and create 2px border so I'm treating each <td> differently. I have succeeded in doing it that way and used nth child to reduce the CSS. However, my question is why a certain logical way that uses even less CSS selectors doesn't 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 the CSS that uses one less selector and should work but somehow all upper cells end up with no 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 it.

like image 880
Mazen Avatar asked Oct 02 '15 11:10

Mazen


1 Answers

The reason you have no top border on your td's is because you aren't declaring a border-style or border-color...

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

should be...

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

You could simplify this greatly by just 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>
like image 86
Turnip Avatar answered Nov 08 '22 20:11

Turnip