Search code examples
csscss-selectorscss-tables

nth-child not working with CSS table-cell


nth-child not working with css table-cell

* { box-sizing: border-box; }

.table {
border: 1px solid black;
display: table;
height: 30px;
width: 200px;
}

.cell {
display: table-cell;
}

.table:nth-child(1) {
background-color: red;
width: 10%;
}

.table:nth-child(2) {
background-color: green;
width: 50%;
}

.table:nth-child(3) {
background-color: blue;
width: 20%;
}
<div class="table">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>


Solution

  • The nth-child selector does not operate from the parent's perspective so can you please add below css and see results

     .table .cell:nth-child(1) {
                    background-color: red;
                    width: 10%;
                    }
    
                    .table .cell:nth-child(2) {
                    background-color: green;
                    width: 50%;
                    }
    
                    .table .cell:nth-child(3) {
                    background-color: blue;
                    width: 20%;
                    }