Nivyan
Nivyan

Reputation: 139

Background color in a table not displaying for empty cells

Screenshot of the issue

I have a table, where I've given a gray background-color to every second row. How do I capture the empty cells here? And why aren't these being captured in this css:

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

Doing td:empty doesn't capture the blocks neither, so I'm a bit stumped.

Here's the html

      <td>
        <tr>
          <td colspan="2">
            <input type="text" placeholder="Add new email" v-model="email" />
            <img @click="addEmailToQ" src="@/assets/Plus.png" />
          </td>
        </tr>
        <!-- <h2>Emails</h2> -->
        <tr style="text-align: left" v-for="(email, key) in emailList" :key="key">
          {{email}}
        </tr>
      </td>

Upvotes: 3

Views: 1334

Answers (2)

Angelo Lucas
Angelo Lucas

Reputation: 637

Make sure you are including <td> in all cells, even empty <td> </td>

tr:nth-child(even) {
        background-color: #dddddd;
      }
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
  </head>
  <body>
    <table style="width:100%">
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Age</th>
      </tr>
      <tr>
        <td></td>
        <td>Smith</td>
        <td></td>
      </tr>
      <tr>
        <td>Eve</td>
        <td></td>
        <td>94</td>
      </tr>
      <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>
      </tr>
      <tr>
        <td>Eve</td>
        <td></td>
        <td>94</td>
      </tr>
      <tr>
        <td>Jill</td>
        <td></td>
        <td>50</td>
      </tr>
      <tr>
        <td>Eve</td>
        <td></td>
        <td>94</td>
      </tr>
    </table>
  </body>
</html>

Upvotes: 1

rx2347
rx2347

Reputation: 1073

Regarding your "error": It has nothing to do with CSS, your markup is simply wrong. <tr> needs to enclose <td>, not the other way around.

Read up on HTML Tables here: https://www.w3schools.com/html/html_tables.asp

Sample code below: Empty cells will have the given background color with your CSS, if given the right markup.

table {
  width:100%;
}

tr:nth-child(even) {
  background-color: #dddddd; 
}
<table>
  <tr>
    <td>Row 1, Cell 1</td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td>Row 2, Cell 1</td>
    <td></td>
    <td></td>
  </tr>
</table>

Upvotes: 2

Related Questions