skip to Main Content

I want to combine the middle two columns in the third row.
But the columns are not combined in the third row.

what should I do ??
what is the error exactly in my code??

table {
  border: 1px solid #999;
}

td {
  height: 20px;
  width: 50px;
}

/* added by editor to visualize the issues */
table {
  border-spacing: 0.5em;
}

td {
  border: 1px dashed red;
}
<table>
  <tr>
    <td colspan="4"></td>
  </tr>

  <tr>
    <td colspan="2"></td>
    <td colspan="2"></td>
  </tr>

  <tr>
    <td></td>
    <td colspan="2"></td>
    <td></td>
  </tr>
</table>

2

Answers


  1. Is this what you want. I have only added a fourth row for test.

    table,
    td {
      border: 1px solid #999;
    }
    
    td {
      height: 20px;
      width: 50px;
    }
    <table>
      <tr>
        <td colspan="4"></td>
      </tr>
    
      <tr>
        <td colspan="2"></td>
        <td colspan="2"></td>
      </tr>
    
      <tr>
        <td colspan='1'></td>
        <td colspan="2"></td>
        <td colspan='1'></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </table>
    Login or Signup to reply.
  2. The issue is, the way that table cell width is defined or calculated. The MDN WebDocs states:

    Table and column widths are set by the widths of table and col elements or by the width of the first row of cells. Cells in subsequent rows do not affect column widths.

    The easiest fix is to remove the width of the table cells. Then add a specific width to the table itself and use table-layout: fixed; which will equally assign the the width to the columns and not based on the first row:

    table {
      border: 1px solid #999;
    }
    
    td {
      height: 20px;
    }
    
    /* added by editor to visualize the issues */
    table {
      border-spacing: 0.5em;
    }
    
    td {
      border: 1px dashed red;
    }
    
    /* add this */
    table {
      table-layout:fixed;
      width: 250px;
    }
    <table>
      <tr>
        <td colspan="4"></td>
      </tr>
    
      <tr>
        <td colspan="2"></td>
        <td colspan="2"></td>
      </tr>
    
      <tr>
        <td></td>
        <td colspan="2"></td>
        <td></td>
      </tr>
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search