Alex Alex - 3 months ago 6
CSS Question

Make <div> tag(s) fill parent <td>

I have a table that is filled dynamically. Each

<td>
could have one or more
<div class="{success,failure}Status">
inside of it. Those status divs are colored green or red based on success or failure.

I want those divs to completely fill the parent
<td>
. Originally, I was using
height: 100%;
, but if there are multiple divs, then this is not good. However, if I remove the height selector, the entries with only one
<div>
are puny. This is seen in the picture below.

How can I ensure that these single
<td>
entries with only a single
<div>
are completely filled?

Here is a code snippet that demonstrates my point:



table, th, td {
border: 1px solid black;
}

.successDiv {
background-color: green;
}

.failureDiv {
background-color: red;
}

<table>
<thead>
<tr>
<td>
Components
</td>
<td>
Step 1
</td>
<td>
Step 2
</td>
<td>
Step 3
</td>
</tr>
</thead>
<tr>
<td>
Name
</td>
<td>
<div class="successDiv">
Success
</div>
</td>
<td>
<div class="successDiv">
Success
</div>
<div class="failureDiv">
Failure
</div>
</td>
<td>
<div class="successDiv">
Success
</div>
<div class="failureDiv">
Failure
</div>
<div class="failureDiv">
Failure
</div>
</td>
</tr>
</table>





In this snippet, the single green success div should fill its parent td. This should not affect the thead or the first td in each row; those are headers.

Answer

You can use :only-child like this.

table, th, td {
  border: 1px solid black;
}

.successDiv {
  background-color: green;
}

.failureDiv {
  background-color: red;
}

.successDiv, .failureDiv {
   height: 30px;
 }

.successDiv:only-child, .failureDiv:only-child {
   height: 60px;
}
<table>
  <thead>
    <tr>
    <td>
      Components
    </td>
      <td>
        Step 1
      </td>
      <td>
        Step 2
      </td>
    </tr>
  </thead>
  <tr>
    <td>
      Name
    </td>
      <td>
          <div class="successDiv">
            Success
          </div>
      </td>
      <td>
          <div class="successDiv">
            Success
          </div>
          <div class="failureDiv">
            Failure
          </div>
      </td>
  </tr>
</table>