2

I need to migrate a table structure created with CSS grid to an html <table> structure.

The CSS grid layout is

grid-template-columns: auto 1fr 1fr 1fr

How can I accomplish the same result using an HTML table element, with appropriate table, tr, td etc CSS?

enter image description here

mbehzad
  • 3,758
  • 3
  • 22
  • 29

1 Answers1

0

grid-template-columns would be applied to each <tr> and table, tbody, td {display: block} added as well. This should work as long as each <tr> has a maximum of 4 <td> or there is only one <tr> that contains all of the <td>. Below are examples of both table structures. Note the presence of <tbody> is implicit since browsers will insert one within a <table> if it's not in the HTML.

table,
tbody,
td {
  display: block;
}

.grid {
  display: grid;
  width: 100%;
  grid-template-columns: auto 1fr 1fr 1fr;
}


/* Not Required */

.A {
  background: tomato;
}

.B {
  background: yellow;
}

.C {
  background: cyan;
}

.D {
  background: lime;
}
<!-- Original Grid Structure 4x3 -->
<div class='grid'>
  <div class='A'>A</div>
  <div class='B'>B</div>
  <div class='C'>C</div>
  <div class='D'>D</div>
  <div class='A'>A</div>
  <div class='B'>B</div>
  <div class='C'>C</div>
  <div class='D'>D</div>
  <div class='A'>A</div>
  <div class='B'>B</div>
  <div class='C'>C</div>
  <div class='D'>D</div>
</div>
<hr>
<!-- Traditional Table Structure 4x3 -->
<table>
  <tbody>
    <tr class='grid'>
      <td class='A'>A</td>
      <td class='B'>B</td>
      <td class='C'>C</td>
      <td class='D'>D</td>
    </tr>
    <tr class='grid'>
      <td class='A'>A</td>
      <td class='B'>B</td>
      <td class='C'>C</td>
      <td class='D'>D</td>
    </tr>
    <tr class='grid'>
      <td class='A'>A</td>
      <td class='B'>B</td>
      <td class='C'>C</td>
      <td class='D'>D</td>
    </tr>
  </tbody>
</table>
<hr>
<!-- Table Structure 12x1 -->
<table>
  <tbody>
    <tr class='grid'>
      <td class='A'>A</td>
      <td class='B'>B</td>
      <td class='C'>C</td>
      <td class='D'>D</td>
      <td class='A'>A</td>
      <td class='B'>B</td>
      <td class='C'>C</td>
      <td class='D'>D</td>
      <td class='A'>A</td>
      <td class='B'>B</td>
      <td class='C'>C</td>
      <td class='D'>D</td>
    </tr>
  </tbody>
</table>
zer00ne
  • 41,936
  • 6
  • 41
  • 68
  • unfortunately in the "Traditional table structure" solution, each row is an independent grid, so depending on the first td's content in each row the columns width would be different. – mbehzad Dec 20 '21 at 07:42
  • @user2520818 The 2nd table would work visually, but not [semantically](https://stackoverflow.com/q/1294493/2813224). – zer00ne Dec 20 '21 at 17:31