Search code examples
htmlcsshtml-table

Align the columns of table to right and left


I am using the table in my application. I have two columns in the table which I need to use for next and previous buttons. I want to keep them in the right corner and left corner. How I can do that?

<table>
  <tr>
    <td colspan="2">
      <a href="#Previous" style="float:left;color:#fff">
        < Back </a>
          <img src="images/icon-previous.png" />
    </td>
    <td style="float:right;margin-left: 208px;">
      <a data-bind="click:$root.Next" style="float:right">
        <img src="images/icon-next.png" />
      </a>
    </td>
  </tr>
</table>

Here is a different version. There are three images. I need to align them as left, center, and right orders using table. Is it possible?

<footer data-role="footer">
  <div style="width:100%">
    <table style="width:100%">
      <tr>
        <td style="text-align:left">
          <img src="images/icon-add1.png" /></a>

          </div>
          </div>

        </td>

        <td style="text-align:center">
          <a><img src="images/icon-add2.png" /></a>
        </td>

        <td style="text-align:right">
          <img src="images/icon-add3.png" /></a>
          </a>
        </td>
      </tr>
    </table>

  </div>
</footer>

Enter image description here


Solution

  • First of all, please fix the HTML errors in your examples in the question, and read on.

    You can set text-align: right; on the second table cell. However it's recommend to avoid using table for layout, an example of using div with flexbox below.

    table {
      border-collapse: collapse;
      border-spacing: 0;
      width: 100%;
    }
    
    td:last-child {
      text-align: right;
    }
    
    div {
      display: flex;
      justify-content: space-between;
    }
    <table>
      <tr>
        <td><a>&lt; Back</a></td>
        <td><a>Next &gt;</a></td>
      </tr>
    </table>
    
    <hr>
    
    <div>
      <a>&lt; Back</a>
      <a>Next &gt;</a>
    </div>

    EDIT

    See the follow example for making a 3-column layout.

    table {
      border-collapse: collapse;
      border-spacing: 0;
      width: 100%;
      table-layout: fixed; /* NEW */
    }
    
    td:nth-child(2) {
      text-align: center; /* NEW */
    }
    
    td:nth-child(3) {
      text-align: right;
    }
    
    div {
      display: flex;
      justify-content: space-between;
    }
    <table>
      <tr>
        <td><a>&lt; Back</a></td>
        <td><a>Middle</a></td>
        <td><a>Next &gt;</a></td>
      </tr>
    </table>
    
    <hr>
    
    <div>
      <a>&lt; Back</a>
      <a>Middle</a>
      <a>Next &gt;</a>
    </div>