Search code examples
htmlcsscellcentering

Avoiding CSS classes on each html table cells?


I have a HTML table where some column cells' text must be left-aligned and centered for other columns. How can I avoid setting CSS classes on each cell? Can one simplify it?

I have created an example on JsFiddle.

Here is the HTML:

<table id="myTbl">
    <colgroup>
        <col class="Col-1">
        <col class="Col-2">
        <col class="Col-3">
    </colgroup>
    <tr>
        <td class="makeItLeft">&nbsp</td><td class="makeItCenter">AAA</td><td class="makeItCenter">BBB</td>
    </tr>
    <tr>
        <td class="makeItLeft">DDD</td><td class="makeItCenter">4</td><td class="makeItCenter">7</td>
    </tr>
    <tr>
        <td class="makeItLeft">EEE</td><td class="makeItCenter">2</td><td class="makeItCenter">6</td>
    </tr>
    <tr>
        <td class="makeItLeft">FFF</td><td class="makeItCenter">2</td><td class="makeItCenter">5</td>
    </tr>
    <tr>
        <td class="makeItLeft">GGG</td><td class="makeItCenter">&#x2713;</td><td class="makeItCenter">88</td>
    </tr>
</table>

Here is the CSS:

#myTbl {
    width: 96%;
    background-color: green;
}

#myTbl td {
    vertical-align:middle;
}

.Col-1 {
    background-color: red;
}

.Col-2 {
    background-color: yellow;
}

.Col-3 {
    background-color: blue;
}

.makeItCenter {
    text-align: center;
}

.makeItLeft {
    text-align: left;
}

Solution

  • Add those line on your Css

    #myTbl tr td:nth-child(2),#myTbl tr td:nth-child(3){
        text-align:center;
    }
    #myTbl tr td:nth-child(1){
        text-align:left;
    }
    

    and remove your below code along with the td classes

    .makeItCenter {
    text-align: center;
    }
    
    .makeItLeft {
     text-align: left;
    }