htmlcsscss-tables

For a 100% table, how to spread elements horizontally evenly inside <td>?


For example, I have a table which the first column has some elements with different length:

<table border="1" style="text-align:center;width:100%;">
  <tr><td><span>a</span></td><td>1</td></tr>
  <tr><td><span>a</span><span>a</span></td><td>1</td></tr>
  <tr><td><span>a</span><span>a</span><span>a</span></td><td>1</td></tr>
  <tr><td><span>a</span><span>a</span><span>a</span><span>a</span><td>1</td></tr>  
<table>

How to add space to elements so that the elements in <td> is evenly distributed?

I tried:

span{
  display:inline-block;
}

.container {
  display: flex;
}
.container.space-around {
  justify-content: space-around;
}
.spaceBetween{
  display:space-between;
}
<table border="1" style="text-align:center;width:100%;">
  <tr class="container space-around"><td class="spaceBetween"><span>a</span></td><td>1</td></tr>
  <tr class="container space-around"><td class="spaceBetween"><span>a</span><span>a</span></td><td>1</td></tr>
  <tr class="container space-around"><td class="spaceBetween"><span>a</span><span>a</span><span>a</span></td><td>1</td></tr>
  <tr class="container space-around"><td class="spaceBetween"><span>a</span><span>a</span><span>a</span><span>a</span></td><td>1</td></tr>  
</table>

but not working.


Solution

  • .spaceBetween {
      display: flex;
      justify-content: space-around;
    }
    <table border="1" style="text-align:center;width:100%">
      <tr class="container space-around">
        <td class="spaceBetween"><span>a</span></td>
        <td>1</td>
      </tr>
      <tr class="container space-around">
        <td class="spaceBetween"><span>a</span><span>a</span></td>
        <td>1</td>
      </tr>
      <tr class="container space-around">
        <td class="spaceBetween"><span>a</span><span>a</span><span>a</span></td>
        <td>1</td>
      </tr>
      <tr class="container space-around">
        <td class="spaceBetween"><span>a</span><span>a</span><span>a</span><span>a</span></td>
        <td>1</td>
      </tr>
    </table>

    You just didn't place your flex in the right place and were completely breaking the table. I've changed it so the flex is applied to the cell.