Reputation: 48686
Can someone help me figure what selectors I need to change the width of my columns globally on my two column table?
Using this, will of course select all cells:
table td {
width: 50px;
}
What I want is this:
<table>
<tr>
<td style="width: 50px">data in first column</td>
<td style="width: 180px">data in second column</td>
</tr>
<tr>
<td style="width: 50px">more data in first column</td>
<td style="width: 180px">more data in second column</td>
</tr>
</table>
I'd like to put the width specification in a style sheet rather then typing the width implicitly for each tag. What CSS selector will let me set the 50px width and 180px appropriately?
Upvotes: 6
Views: 27543
Reputation: 1342
I think your best bet would be to use css pseudo-selectors:
table tr td:first-child {
width: 50px;
}
table tr td:last-child {
width: 150px;
}
td {
background: gray;
}
<table>
<tr>
<td>data in first column</td>
<td>data in second column</td>
</tr>
<tr>
<td>more data in first column</td>
<td>more data in second column</td>
</tr>
</table>
Here's an example on JSFiddle: http://jsfiddle.net/scottm28/gGXy6/11/
Alternatively, you could also use CSS3 :nth-child() Selector
Upvotes: 0
Reputation: 7466
Try using class
names in your markup and utilizing colgroup
. It's by far the least hassle since you define the width only in colgroup
, and is cross-browser compatible.
Eg.
<table>
<colgroup>
<col class="colOne" />
<col class="colTwo" />
</colgroup>
<tr>
<td>data in first column</td>
<td>data in second column</td>
</tr>
<tr>
<td>more data in first column</td>
<td>more data in second column</td>
</tr>
</table>
/* CSS */
.colOne{
width: 50px;
}
.colTwo{
width: 180px;
}
See fiddle: http://jsfiddle.net/4ebnE/
One thing though, colgroup
is deprecated in HTML5. But then again HTML5 isn't standardized yet, so you can make the call.
Oh, and it's possible to do without any CSS if you fancy:
<table>
<colgroup>
<col width="50"/>
<col width="180" />
</colgroup>
<tr>
<td>data in first column</td>
<td>data in second column</td>
</tr>
<tr>
<td>more data in first column</td>
<td>more data in second column</td>
</tr>
</table>
Upvotes: 4