Referring to columns


#1

What is the best way to refer to a column in a table so you can format it?

When I look online for how to align text in a column, the examples show something like this…

th{
text-align: left
}

But what if I have a tabe with 6 columns, and I want the 1st col left-aligned, the 2nd-4th centered, and the last two columns right-aligned?

I tried this but it doesn’t work:

<colgroup>
  <col id="feature">
  <col id="basic">
  :
</colgroup>
col#feature{
text-align: left;
}

#2

Hi,
That is where Pseudo-classes can help you, alternatively you could place classes on your <th> and <td> but psuedos will keep your html cleaner and do the job just as well.

For the first column to be left aligned just use :first-child

If you want the last two right aligned use :nth-last-child to count from the end.

For all others center aligned just style them in your default th and td styles.

table

<!DOCTYPE HTML>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Test Page</title>
<style>
html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}
.member-plans {
  border-collapse: collapse;
  min-width: 600px; /*just adding some extra space for the test case*/
}
.member-plans th,
.member-plans td{
  border: 1px solid #AAA;
  text-align: center;
}
.member-plans th:first-child,
.member-plans td:first-child {
  text-align: left;
}
.member-plans th:nth-last-child(1), /*same as :last-child*/
.member-plans th:nth-last-child(2),
.member-plans td:nth-last-child(1), /*same as :last-child*/
.member-plans td:nth-last-child(2) {
  text-align: right;
}
</style>

</head>
<body>

<table class="member-plans">
          <!-- Column Headings -->
          <tr>
            <th>Feature</th>
            <th>Guest</th>
            <th>Basic<br>Access</th>
            <th>Premium<br>Access</th>
            <th>Premium<br>+ eBook</th>
            <th>Last Header</th>
          </tr>

          <!-- Rows -->
          <tr>
            <td>News</td>
            <td>X</td>
            <td>X</td>
            <td>X</td>
            <td>X</td>
            <td>Last Row</td>
          </tr>
          <tr>
            <td>Articles</td>
            <td>X</td>
            <td>X</td>
            <td>X</td>
            <td>X</td>
            <td>Last Row</td>
          </tr>
        </table>

</body>
</html>

#3

@Ray.H,

Thanks for the new tip!

What if I need to do something fancier where I can’r rely on the left most and right most columns?

Let’s say I had 10 columns and the 2nd, 3rd, 6th, 7th needed to be right aligned, yet the 1st and 4th left aligned and the 5th, 8th, 9th and 10th needed to be centered?


#4

If you know the column count you’ll always be able to target with :nth-child

You can always add classes though if :nth-child or :nth-last-child makes your head hurt :slightly_smiling_face: