简体   繁体   中英

How to make <table> column right-aligned

<table>
  <colgroup>
    <col>
    <col style='text-align:right'>
  </colgroup>
  <tbody>
    <tr>
      <td>Sample text</td>
      <td>This text should be right-aligned</td>
    </tr>
    <tr>
      <td></td>
      <td>
        <div id='spacer' style='width:100px'>
          I'm a spacer
        </div>
      </td>
    </tr>
  </tbody>
</table>

Results in text that isn't right aligned. If the same style is applied to the td element it works fine. How do I right-align text in a column without having to apply a style to every td element?

Add the following CSS:

table.tableClass tr td:nth-child(2) {
   text-align: right;
}

the number after nth-child( is the column, so for this case it would be 2 because it's the second column. Fiddle: http://jsfiddle.net/p97vdo2p/1/

HTML isn't rendered by column, it's rendered by rows. That's why there <tr></tr> (table rows) exist, but <tc></tc> (table columns) do not. That being said, the easiest way to style a column in HTML, is by applying the same CSS class to every <td></td> in the given column. You can type in the same class to every one manually, or you could write it programmatically, via javascript or a server-side script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM