Best
Best

Reputation: 2318

Center image in table td in CSS

I've been trying to align an image to the center of the table td. It worked with setting margin-left to a specific value but it also increased the size of td too and that isn't exactly what I wanted

Is there any efficient ways of doing this? I used percentages for the height and witdh of the table.

Upvotes: 132

Views: 494005

Answers (11)

ekcrisp
ekcrisp

Reputation: 1911

If there are rows in the table that have a colspan set to a value greater than 1, you may need to add the same colspan to the <td> tag containing the image

Upvotes: 0

y.z
y.z

Reputation: 31

Improving @aulianza answer this is just fine for my case (without display: block)

td img{
    margin-left: auto;
    margin-right: auto;
}

Thanks!

Upvotes: 0

Muhammad
Muhammad

Reputation: 1350

Center a div inside td using margin, the trick is to make the div width the same as the image width.

<td>
  <div style="margin: 0 auto; width: 130px">
    <img src="me.jpg" alt="me" style="width: 130px" />
  </div>
</td>

Upvotes: 12

user13731874
user13731874

Reputation: 11

Another option is the use <th> instead of <td>. <th> defaults to center; <td> defaults to left.

Upvotes: 1

aulianza
aulianza

Reputation: 51

td image 
{
    display: block;
    margin-left: auto;
    margin-right: auto;
}

Upvotes: 5

Kheteswar
Kheteswar

Reputation: 191

As per my analysis and search on the internet also, I could not found a way to centre the image vertically centred using <div> it was possible only using <table> because table provides the following property:

valign="middle"

Upvotes: -5

oqx
oqx

Reputation: 2377

<table style="width:100%;">
<tbody ><tr><td align="center">
<img src="axe.JPG" />
</td>
</tr>
</tbody>
</table>

or

td
{
    text-align:center;
}

in the CSS file

Upvotes: 6

Mohammed Gadiwala
Mohammed Gadiwala

Reputation: 2063

Simple way to do it for html5 in css:

td img{
    display: block;
    margin-left: auto;
    margin-right: auto;

}

Worked for me perfectly.

Upvotes: 89

Scott
Scott

Reputation: 21882

<td align="center">

or via css, which is the preferred method any more...

<td style="text-align: center;">

Upvotes: 217

Kheteswar
Kheteswar

Reputation: 191

This fixed issues for me:

<style>
.super-centered {
    position:absolute; 
    width:100%;
    height:100%;
    text-align:center; 
    vertical-align:middle;
    z-index: 9999;
}
</style>

<table class="super-centered"><tr><td style="width:100%;height:100%;" align="center"     valign="middle" > 
<img alt="Loading ..." src="/ALHTheme/themes/html/ALHTheme/images/loading.gif">
</td></tr></table>

Upvotes: 8

Michiel
Michiel

Reputation: 8093

Set a fixed with of your image in your css and add an auto-margin/padding on the image to...

div.image img {
    width: 100px;
    margin: auto;
}

Or set the text-align to center...

td {
    text-align: center;
}

Upvotes: 6

Related Questions