2012-11-11 111 views
1

在頁面中,我有許多HTML表格,其中有許多列。我需要對它們應用不同的風格。所有的列將有不同的寬度,但在表格中它們將是相同的,我的意思是所有表格的第一列將相同,第二列和所有列相同。使用css自動將不同列樣式應用於表列

CSS是應用在表上,但不是在列上,有沒有一種方法,我只是添加CSS類,我可能沒有把它們應用在HTML代碼中,它們會自動應用。可能使用 僞列或其他方式?

+0

我不認爲你可以沒有任何服務器端編程或使用JavaScript。 – scaryguy

+0

如何生成表格?您可以在打印時添加課程嗎?如果不是,你可以使用CSS3選擇器嗎?還是隻有CSS2? –

回答

4

如果你能使用支持CSS nth-child()瀏覽器,你可以使用:

tr td:nth-child(even) { 
    background-color: #ffa; 
} 

JS Fiddle demo

在我使用:nth-child(even)避免造型的第一td元素(其中包含的行標題)上面的演示中,你可以,當然,包含行中的th元素標題(這很可能是更多的語義正確的),或者樣式的odd列(或oddtd元素),但不:first-child,該:not()選擇可用:

tr td:nth-child(odd):not(:first-child) { 
    background-color: #ffa; 
} 

JS Fiddle demo

如果你具有支持舊的瀏覽器,不支持:nth-child()僞類限制,您可以使用相鄰兄弟選擇(雖然這是少維護):

td + td, /* styles the second td */ 
td + td + td + td { /* styles the fourth td */ 
    background-color: #ffa; 
} 

td + td + td { /* styles the third td */ 
    background-color: #fff; 
} 

JS Fiddle demo

Thoug它會更容易些類(即使只提供給oddeven)樣式:

.even { /* styles the cells with the class of 'even' */ 
    background-color: #ffa; 
} 

.even + td { /* styles the cell that follows the cell with the 'even' class */ 
    background-color: #f90; 
} 

您也可以使用colgroupcol元素來定義類你列:

<table> 
    <colgroup> 
     <col class="first" /> 
     <col class="second" /> 
     <col class="third" /> 
     <col class="fourth" /> 
    </colgroup> 
    <thead> 
     <tr> 
      <th></th> 
      <th>Column one</th> 
      <th>Column two</th> 
      <th>Column three</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td>Row one</td> 
      <td>row one, cell one</td> 
      <td>row one, cell two</td> 
      <td>row one, cell three</td> 
     </tr> 
     <tr> 
      <td>Row two</td> 
      <td>row two, cell one</td> 
      <td>row two, cell two</td> 
      <td>row two, cell three</td> 
     </tr> 
    </tbody> 
</table> 

用下面的CSS作爲一個例子(注意這裏沒有理由不樣式其他col CL驢,我只是選擇了不要在這個演示):

.second, .fourth { 
    background-color: #ffa; 
}​ 

JS Fiddle demo

參考文獻:

0

您可以使用CSS3「第n」選擇器,但它不適用於舊版瀏覽器。 所以你最好的解決方案是在頁面加載後在javascript中應用更改(使用jQuery實例)。

$(function() { 
    $("table tr td:nth-child(n)").css('width', '100px'); 
}); 

,或者你可以添加一個類

$("table tr td:nth-child(n)").addClass("myWidth1"); 

,並在你的CSS

.myWidth1{ width: 100px } 

確認表選擇捕獲所有表。