2013-03-09 6 views
6

Kann mir jemand helfen, herauszufinden, welche Selektoren ich brauche, um die Breite meiner Spalten global in meiner zweispaltigen Tabelle zu ändern?CSS-Selektor zum Auswählen erster und zweiter Tabellenzellen

diese verwenden, werden natürlich alle Zellen auswählen:

table td { 
    width: 50px; 
} 

Was ich will, ist dies:

<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> 

Ich möchte die Breitenangabe in einem Stylesheet setzen eher dann eingeben die Breite implizit für jedes Tag. Mit welchem ​​CSS-Selektor kann ich die Breite 50px und 180px passend einstellen?

Antwort

16

Ja.

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

td:nth-child(2){ 
    width: 180px; 
} 

oder, wie von Brainslav der Bearbeitung vorgeschlagen:

td:nth-child(1) { 
     width: 50px;} 
td:nth-child(2) { 
     width: 180px;} 

link

3

Versuchen class Namen in Ihrem Markup und colgroup nutzen. Es ist mit Abstand am wenigsten Aufwand, da Sie die Breite nur in colgroup definieren und Cross-Browser-kompatibel ist.

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; 
} 

Siehe Geige: http://jsfiddle.net/4ebnE/

Eine Sache, aber colgroup in HTML5 ist veraltet. Aber dann wieder HTML5 ist noch nicht standardisiert, so dass Sie den Anruf tätigen können.

Oh, und es ist möglich, ohne CSS zu tun, wenn Sie Lust haben:

<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> 
+0

Große Antwort! Noch besser: Colgroup ist in [HTML5] nicht veraltet (https://www.w3.org/TR/html5/tabular-data.html#the-colgroup-element). –

0

Ich denke, die beste Wahl wäre CSS Pseudo-Selektoren zu verwenden:

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> 

Hier ist ein Beispiel auf JSFiddle: http://jsfiddle.net/scottm28/gGXy6/11/

Alternativ können Sie auch CSS3 :nth-child() Selector verwenden

Verwandte Themen