Reputation: 19607
I'm using a PHP script to automatically resize pictures proportionally so they fit a given height and width (ex: original picture is 200x100px, target box is 180x180px, resized image is 180x90px).
It works fine but the usual CSS tricks used to center an image inside a div seem to require you knowing the dimensions in advance.
The only workaround I've found is to define an outer div to display:table;
and the div containing an image to display: table-cell;vertical-align: middle;text-align:center;
.
Is there another way ?
Upvotes: 1
Views: 1486
Reputation: 15204
Not the best practice text-align to align images.
"The tricky thing about the text-align property is that you can only align text with it - you can't use it to move block-level elements like images. Some browsers will align images or tables with this property, but it's not reliable, as you've found." --Jennifer Kyrnin, About.com
You can use the deprecated img's attribute align="center", Although you won't use. This way tags and style are mixed, and, to worsen, there are vertical and horizontal spaces around the full image.
<img src="http://www.lorempixel.com/100/150" align="center"> <-- Wrong way
The best way to solve this is using css. Setting the image as div's background then the div's space will be your image's space and you can use margins to put it in place. You can try to use one of these others techniques CSS Tricks's Absolute center an image
CSS background-image Technique:
background:url('path_to_img') center center no-repeat; /* div center */
background:url('path_to_img') center 0 no-repeat; /* div horizontal center */
background:url('path_to_img') 0 center no-repeat; /* div vertical center */
Upvotes: 4
Reputation: 557
If you need to use an img tag, and do not want to mess with divs with background images, you can try this method:
.container
{
width: 180px;
height: 180px;
background-color: #FF0000;
line-height: 180px;
font-size: 0;
text-align: center;
}
.container img {
vertical-align: middle;
}
font-size is set to 0 to avoid weird spacing. Having line-height equal to the height of your container, causes vertical-align to work as a vertical center, at least for images.
The benefit of this is that you will be able to put your images in img tags, which is more semantically pleasing than background images. This method works when you have a known container size, but an unknown image size that you wish to center inside.
Edit: Here's a link to another fiddle: http://jsfiddle.net/Nz6Nm/4/
You mentioned possibly needing to put text above the image, so I just wanted so show a quick way of doing it. This way adds 20px to the top. If you need to stick with the 180 x 180, then you can adjust the logic to fit.
Upvotes: 3