問題描述

我想在表中對最後一個TD進行風格,而不需要在特定的TD上使用CSS類。

<table>
  <tbody>
    <tr>
      <td>One</td>
      <td>Two</td>
      <td>Three</td>
      <td>Four</td>
      <td>Five</td>
    </tr>
  </tbody>
</table>

table td
{
  border: 1px solid black;
}

我想要TD包含文本”Five”沒有邊框,但是再次,我不想使用一個類。

最佳解決方案

您可以使用相關規則:

table td + td + td + td + td {
  border: none;
}

只有在運行時沒有確定列數時,這才有效。

次佳解決方案

:last-child選擇器應該做,但它是not supported in any version of IE

我恐怕別無選擇,只能用一個課。

第三種解決方案

您可以使用:last-of-type pseudo-class:

tr > td:last-of-type {
    /* styling here */
}

有關更多信息和與不同瀏覽器的兼容性,請參閲the MDN。查看W3C CSS guidelines瞭解更多信息。

第四種方案

如果你已經在使用JavaScript,看看jQuery。它支持瀏覽器獨立的”last-child”選擇器,你可以這樣做。

$("td:last-child").css({border:"none"})

第五種方案

你可以使用last-child psuedo類

table tr td:last-child {
    border: none;
}

這將僅僅是最後一個td的風格。它尚未完全支持,因此可能不適用

第六種方案

嘗試:

tr:last-child td:last-child{
    border:none;
    /*any other style*/
}

這隻會影響表中最後一個td元素,假設是唯一的(否則,你只需要識別你的表)。儘管如此,如果您將更多的內容添加到表中,那麼它將會適應最後一個TD。所以如果是一個特定的情況

td:nth-child(5){
    border:none;
}

應該夠了

第七種方案

Javascript是唯一可行的方法來做這個客户端(即CSS不會幫助你)。在jQuery中:

$("table td:last").css("border", "none");

第八種方案

您可以使用HTML 4.0(link)中指定的col元素。它適用於每個瀏覽器。你可以給它一個ID或一個類或一個內聯樣式。只需要注意的是它會影響所有行的整個列。例:

<table>
    <col />
    <col width="50" />
    <col id="anId" />
    <col class="whatever" />
    <col style="border:1px solid #000;" />
    <tbody>
        <tr>
            <td>One</td>
            <td>Two</td>
            <td>Three</td>
            <td>Four</td>
            <td>Five</td>
        </tr>
    </tbody>
</table>

第九種方案

在jQuery中,只要在執行以下操作之前靜態或動態創建表:

$("table tr td:not(:last-child)").css({ "border-right":"1px solid #aaaaaa" });

只需在表格列中的每個單元格添加一個右邊框,除了最後一個單元格。

參考文獻

注:本文內容整合自Google/Baidu/Bing輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇