Search code examples
csscenter

CSS left text, centered image in table


I'm pretty new to CSS and cannot figure out how to accomplish the following. I have tabular data. Some of the data elements have images associated with them. I want text in the cell left justified and I want the images in the same cell centered.

In other words, I want the same result as the following except inside a table cell.

<p>Some text.</p>
<img style="display:block;margin-left:auto;margin-right:auto;" src="myimage.jpg"/>

How can I accomplish this? When I try placing this inside a td element, both the text and the image are at the left side.


Solution

  • To use margin to center an element you need to have a set width:

    <p style="text-align: left;">Some text.</p>
    <img style="display:block;margin-left:auto;margin-right:auto; width:200px;" src="myimage.jpg"/>
    

    Also, consider putting your styles in an external stylesheet and use selectors to target your elements.