Question

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;
}
Was it helpful?

Solution 2

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

OTHER TIPS

You can make a general rule to set alignment to center, and then override the first column with a left alignment:

#myTbl td {
    text-align: center;
}

#myTbl td:first-child {
    text-align: left;
}

Use the power of CSS Pseudo-Class Selectors:

#myTbl td {
    text-align: center;
}

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

CSS Pseudo-Class selectors allow you to choose various things like first-of-type, first-child, nth-child, last-child, only-of-type, and more, for these sticky situations. The above code will set the rule of centering the content of all the tds, which are all children of trs. Then, for each first td child of each tr, it will override the centering with a left-align rule.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top