Search code examples
htmlcsshtml-tablealignment

How to center align a <td> in a <tr>?


I have the following code, which shows four images in a table. The reason for the float: left; CSS is so that they wrap. JSFiddle

<table>
    <tr>

        <td style="float: left; padding: 20px;">
            <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=600%C3%97300&w=600&h=300" />
            <div style="padding-top: 30px;">TEST TEXT #1</div>
        </td>

        <td style="float: left; padding: 20px;">
            <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=600%C3%97300&w=600&h=300" />
            <div style="padding-top: 30px;">TEST TEXT #2</div>
        </td>

        <td style="float: left; padding: 20px;">
            <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=600%C3%97300&w=600&h=300" />
            <div style="padding-top: 30px;">TEST TEXT #3</div>
        </td>

        <td style="float: left; padding: 20px;">
            <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=600%C3%97300&w=600&h=300" />
            <div style="padding-top: 30px;">TEST TEXT #4</div>
        </td>

    </tr>
</table>

However, they currently are fixed to the left of the table row (which is understandable, hence the float: left CSS). However, is there a way that I can get the wrapping effect of the floating while having the <td> elements center aligned inside the <tr> element?

And yes, I do have to use a table.


Solution

  • Instead of floating the td, you can use display: flex; flex-wrap: wrap; on the tr and that will cause the same behavior. Then you can use justify-content: center; to center the td's.

    tr {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
    }
    <table>
      <tr>
    
        <td style="padding: 20px;">
          <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=600%C3%97300&w=600&h=300" />
          <div style="padding-top: 30px;">TEST TEXT #1</div>
        </td>
    
        <td style="padding: 20px;">
          <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=600%C3%97300&w=600&h=300" />
          <div style="padding-top: 30px;">TEST TEXT #2</div>
        </td>
    
        <td style="padding: 20px;">
          <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=600%C3%97300&w=600&h=300" />
          <div style="padding-top: 30px;">TEST TEXT #3</div>
        </td>
    
        <td style="padding: 20px;">
          <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=600%C3%97300&w=600&h=300" />
          <div style="padding-top: 30px;">TEST TEXT #4</div>
        </td>
    
      </tr>
    </table>