Home > database >  Is it possible to center text in a table with an image?
Is it possible to center text in a table with an image?

Time:10-18

I would like to have the table image and text vertically and horizontally centered in the same cell. I've tried text-align and vertical-align, but the text will just display before or after the image. Can the text be set to be in the center of the cell with the image like this example?

Example

CSS:

th {
text-align: center;
vertical-align: middle;
}

HTML:

<table>
    <tr>
        <th><img src="https://www.w3schools.com/HOWTO/img_snow_wide.jpg" alt="Snow" style="width:100%;">CENTERED</th>
    </tr>
</table>

CodePudding user response:

Probably you are talking about background image and background size property here as:

th {
    background-image: url(https://www.w3schools.com/HOWTO/img_snow_wide.jpg);
    background-size: contain;
    font-size: 24px;
    font-weight: bold;
  }

working code: https://codesandbox.io/s/pensive-panna-qbnkut?file=/index.html:345-531

Other way is to position absolute a div containing text at the center of the 'th' element and use 'img' element as you used now.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
    <style>
      table {
        width: 100vh;
        height: 50vh;
        margin: 0 auto;
      }
      th {
        background-image: url(https://www.w3schools.com/HOWTO/img_snow_wide.jpg);
        background-size: contain;
        font-size: 24px;
        font-weight: bold;
      }
    </style>
  </head>
  <body>
    <table>
      <tr>
        <th>
          CENTERED Text
        </th>
      </tr>
    </table>
  </body>
</html>

CodePudding user response:

If you want to add the image and text content on the table head then only use <th> tag otherwise it is good to use <td> tag inside <tr> for semantic meaning as <td> tag represent table data.

  • Related