Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to globally text-align a table column without specifying a class in each row?

Tags:

jquery

css

Wondering what the best way to make this more efficient, perhaps with jQuery. I am ok with solutions not compliant with ie7, even lack of support for ie8 might be ok if necessary.

<style type="text/css">
.cal {text-align:center}
.ral {text-align:right}
</style>
<table>
 <th>
  <td class="cal">center</td>
  <td>left</td>
  <td class="cal">center</td>
  <td>left</td>
  <td class="ral">right</td>
 </th>
 <tr>
  <td class="cal">center</td>
  <td>left</td>
  <td class="cal">center</td>
  <td>left</td>
  <td class="ral">right</td>
 </tr>
 <tr>
  <td class="cal">center</td>
  <td>left</td>
  <td class="cal">center</td>
  <td>left</td>
  <td class="ral">right</td>
 </tr>
</table>
like image 581
chrisrth Avatar asked Apr 18 '12 00:04

chrisrth


People also ask

How do you align text in a table column in HTML?

To place an item at the top or bottom of its cell, insert the "VALIGN=" attribute within the code for that cell. To vertically align an entire row (e.g., placing all data in that row at the tops of the cells), insert the "VALIGN=" attribute within the code for that row.

How many ways can you align text in a table cell?

There are four main alignments: left, right, center, and justified.

How do I align text in a table?

Select the text and go to the Layout tab and the Alignment section of the ribbon. Choose “Align Center.” Your text will then be right in the middle of the cell. Centering the text in your Word table is a simple task whether horizontally, vertically, or both.

Which property is used to align the text in a table?

The text-align property in CSS is used to specify the horizontal alignment of text in an element ie., it is used to set the alignment of the content horizontally, inside a block element or table-cell box.

Which attribute is used to align the text to middle of the cell in table?

To center align text in table cells, use the CSS property text-align.


1 Answers

You could add a class to the fifth td in each row using jQuery, and style the class to align text to the right.

Alternatively (and the way I do it) is using the nth child selector.

tr td:nth-child(odd) {
    text-align: center;
}

tr td:nth-child(5) {
    text-align: right;
}

it's not compatible with IE 8.0, but it is a lot simpler than a JavaScript based solution.

like image 140
djlumley Avatar answered Dec 19 '22 07:12

djlumley