0

Given this code (coloring every other row's background to blue) how can you make it so it colors the full row in, not just where you got 'td'-s (in this example the Data 1 row)?

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    table{
      border: 5px solid;
    }    
    tr:nth-child(even) {background-color: blue;}
    




  </style>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <table class="mytable">
      <tr>
        <td>Column 1</td>
        <td>Column 2</td>
      </tr>
      <tr>
        <td>Data 1</td>
        
        
      </tr>
      <tr>
        <td>Data 3</td>
        <td>Data 4</td>
      </tr>

      <tr>
        <td>Data 5</td>
        <td>Data 6</td>
        <td>Data 7</td>

      </tr>
    </table>
  </body>
</html>

Image of html

harvy666
  • 3
  • 3
  • Add empty `` or use [`colspan`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#attr-colspan) – User863 Jan 17 '23 at 11:08
  • Not sure that is actually possible without colspan. Can't you put empty table cells in those places? – CBroe Jan 17 '23 at 11:08
  • I did the js code to correct the colspan issue but since now the question is closed I can't post it – Diego D Jan 17 '23 at 11:34

1 Answers1

0

Use:

  • border-collapse: collapse to remove the default table's cell spacing
  • colspan where needed, to extend the desired cells
  • Use <thead> and <tbody>. The browser will insert TBODY automatically, so make use of it.

table {
  border: 5px solid;
  border-collapse: collapse;
}

tr:nth-child(even) {
  background-color: blue;
}
<table class="mytable">
  <thead>
    <tr>
      <td>Column 1</td>
      <td>Column 2</td>
      <td>Column 3</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td colspan="3">Data 1</td>
    </tr>
    <tr>
      <td>Data 3</td>
      <td colspan="2">Data 4</td>
    </tr>
    <tr>
      <td>Data 5</td>
      <td>Data 6</td>
      <td>Data 7</td>
    </tr>
  </tbody>
</table>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313