HTML Tabelle zweifarbig?

4 Antworten

Weise den td-Elementen einen CSS-Klassenselektor zu, in dem du die Farbe definierst.

Ein Beispiel:

HTML:

<table>
  <thead>
    <tr>
      <th>Colum 1</th>
      <th>Colum 2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="columnOne">Some text</td>
      <td class="columnTwo">Some other text</td>
    </tr>
    <tr>
      <td class="columnOne">Some text</td>
      <td class="columnTwo">Some other text</td>
    </tr>
  </tbody>
</table>

CSS:

.columnOne {
  background-color: blue;
}

.columnTwo {
  background-color: red;
}

Fiddle: https://jsfiddle.net/vzbpmugf/

Du kannst den entsprechenden Zellen entweder eine class geben um dieser mit css dann eine Farbe zuzuweisen.

<table>
 <tr>
  <td class="blau"></td>
  <td class="rot"></td>
 </tr>
 <tr>
  <td class="blau"></td>
  <td class="rot"></td>
 </tr>
</table>

css:

.blau {
  background-color: blue;
}
.rot {
  background-color: red;
}

Oder du kannst auch mit css Befehlen wie :first-child oder :nth-child() bestimmte Elemente inerhalb der Tabelle ansprechen um ihnen eine Farbe zuzuordnen.
https://www.w3schools.com/cssref/sel_firstchild.asp
https://www.w3schools.com/cssref/sel_nth-child.asp

regex9  20.10.2018, 17:47

Stimmt, damit geht es dann auch kürzer. Die class-Attribute kann man sich sparen.

td:nth-child(odd) {
  background-color: blue;
}

td:nth-child(even) {
  background-color: red;
}
2
medmonk  21.10.2018, 11:29
@regex9

Es geht noch etwas kürzer ;)

td {
 background: blue; 
}

td:nth-child:(even) {
 background: red;
}

Eine Farbe als Default definieren und bei bedarf mit nth-child überschreiben (Kaskade). ;)

1

Markup:

<table class="table example">
 <thead>
  <tr>
   <th>First-Column</th>
   <th>Last-Column</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>Some data here...</td>
  <td>...other data here!</td>
</tr>
  <tr>
   <td>Some data here...</td>
   <td>...other data here!</td>
  </tr>
 </tbody>
</table>

CSS:

.table td {
 /* define a default color */
 background-color: blue;
}

.example td:nth-child(even) {
 /* override the default color */
 background-color: red;
}

Pseudo-Selektor nth-child:

https://developer.mozilla.org/de/docs/Web/CSS/:nth-child

LG medmonk

Woher ich das weiß:Berufserfahrung

Entweder alles markieren, was gleichfarbig sein soll und die Hintergrundfarbe ändern oder von vornerein eine farbige Tabelle erstellen und dann dort die Daten eintragen.

Woher ich das weiß:eigene Erfahrung