Home > OS >  Align text on the left, image floating on the right and vertically centered inside a <td>
Align text on the left, image floating on the right and vertically centered inside a <td>

Time:10-10

As the title says, I have an HTML table with some columns. In one of these columns, which has width: auto I would like to display the text left aligned and and an image/icon right aligned and floating, because the image is optional (i.e. some rows may not have it and I want the text to use all the available space in the <td> in that case).

Here's the JSFiddle example: Problem 1

  • When reducing the browser window width (and hence the table width), the text doesn't split on a new line keeping the image on the right.

    Problem 2

  • The image should keep a small padding on the left to not go over the text. Which is the best way to handle this?

    CodePudding user response:

    Add class to respective td (let assume xyz). And add some flex properties to the class.

    <td class="xyz">Lemon soda<img src=""></td>
    
    .xyz { 
        display: flex; 
        align-items: center; 
        justify-content: space-between // or space-around (if you need some space);
    }
    

    Note: Remove img style from css or else it will affect the solution.

    CodePudding user response:

    As a solution, you can use position: absolute and align by vertically with transform: translateY(). And in table tbody td:nth-child(2) add padding-right to create extra space for the icon.

    table tbody td:nth-child(2) {
      text-align: left;
      padding-right: 2em; /* new line */
      position: relative; /* new line */
    }
    
    img {
      position: absolute; /* new line */
      right: 0; /* new line */
      top: 50%; /* new line */
      transform: translateY(-50%); /* new line */
      /* float: right; */
      padding-right: 2px;
    }
    

    • Related