第一个表列的CSS样式,该列的第一个单元格除外

时间:2013-04-04 15:23:10

标签: css css-selectors html-table fixed-width

所以这是<table>

<table class='census'>
    <tr>
        <th colspan="2">My Title</th>
    </tr>
    <tr>
        <td colspan="2" class='chart'><SOME PIE CHART, GENERATED WITH JS></td>
    </tr>
    <tr>
        <td>Some title</td>
        <td>Some Data</td>
    </tr>
    <tr>
        <td>Some title</td>
        <td>Some Data</td>
    </tr>
    <tr>
        <td>Some title</td>
        <td>Some Data</td>
    </tr>
    <tr>
        <td>Some title</td>
        <td>Some Data</td>
    </tr>
    <tr>
        <td>Some title</td>
        <td>Some Data</td>
    </tr>
</table>

我需要为第一列设置固定宽度。它可以轻松完成:

.census td:first-child {
    background-color: #F0F8FE;
    width: 250px;
}

现在问题! 带有JS PIE CHART的固定宽度螺钉。

所以我需要对所有第一个<td>标签应用固定宽度,但colspan="2"包含我的图表的标签除外。

如果这样的话,我唯一想到的就是(到目前为止):

.census td:first-child:not(.chart) {
    background-color: #F0F8FE;
    width: 250px;
}

它给我带来了意想不到的结果。 我现在迷路了。

4 个答案:

答案 0 :(得分:5)

你能不能只是把它放在它后面的图表类上。

   .census td:first-child {
        background-color: #F0F8FE;
        width: 250px;
    }

    .census td.chart {
      width: auto;
      etc...
    }

答案 1 :(得分:1)

如果您正在寻找跨浏览器兼容的方法,我会坚持使用jQuery:

$('td:first-child:not([colspan=2])').css('width', '250px');

示例:http://jsfiddle.net/mZNGj/1/

答案 2 :(得分:1)

在我看来,这是利用caption / thead / tbody / tfoot元素的好时机:

http://jsfiddle.net/Ny6YZ/

tbody td:first-child {
    width: 250px;
}

<table class='census'>
    <caption>My Title</caption>

    <thead>
        <tr>
            <td colspan="2" class='chart'>SOME PIE CHART, GENERATED WITH JS</td>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td>Some title</td>
            <td>Some Data</td>
        </tr>
        <tr>
            <td>Some title</td>
            <td>Some Data</td>
        </tr>
        <tr>
            <td>Some title</td>
            <td>Some Data</td>
        </tr>
        <tr>
            <td>Some title</td>
            <td>Some Data</td>
        </tr>
        <tr>
            <td>Some title</td>
            <td>Some Data</td>
        </tr>
    </tbody>
</table>

虽然,饼图可能更适合tfoot而不是thead。

或者,您可以在colspanned元素上覆盖它:

http://jsfiddle.net/Ny6YZ/1/

td:first-child {
    width: 250px;
}

td[colspan] {
    width: auto;
}

答案 3 :(得分:0)

cimmanon中的一点,(使用更多的表布局助手)但有点不同:

我会尝试定义cols:

<table class='census'>
    <col class="col1"></col>
    <col class="col2"></col>
    <thead>
        <th colspan="2">My Title</th>
    </thead>
    <tr>
        <td colspan="2" class='chart'>SOME PIE CHART, GENERATED WITH JS</td>
    </tr>
    <tr>
        <td>Some title</td>
        <td>Some Data</td>
    </tr>
    ....

并在那里设置宽度:

.col1 {
    background-color: papayawhip;
    width: 250px;
}

具有colspan set的tds不受col

的宽度的影响

demo