PDA

View Full Version : Display an image in a DIV?



chronozphere
30-09-2010, 04:17 PM
Hey everybody,

Stumbled upon another question regarding webdesign. I would like to display an image in a div with a fixed size. The image however, can have an arbitrary size. How can I display this image, so that it is centered and takes maximum space while keeping the original width/height proportions?

Thanks! :)

WILL
30-09-2010, 05:06 PM
Well you'd have to use PHP here. Take your original width and height compare each to the max width and height if the image's original h or w is greater than the max then set it to the max value then calculate what the difference would be for the other.

You could try setting only the width or height of the image in the img tag, but I'm not 100% sure that it would keep the ratio and not distort it. If so though it may save you some calculations in PHP code.

Traveler
30-09-2010, 08:24 PM
Agreed, you can use php to retrieve image information, or even to resize images, but it's not a requirement.


<div style="width : 100px;height : 100px;"><img src="yourimage.jpg" height="100%"></div>


I believe the code above does what you want, but mind you that it will somewhat distort larger images.

grudzio
01-10-2010, 06:27 PM
If you do not have to use img element, you can use the background attribute of the div. Something like this:


<div style="width:100px;height:100px;background:url(image.jpg) no-repeat center center"></div>

If you do need the img tag, here is a link how to do it so it works in (probably) all browsers.
http://www.brunildo.org/test/img_center.html

WILL
02-10-2010, 08:35 AM
These last 2 methods would still distort the image somewhat though, would it not? At the very least the end user's browser would have to download the whole image and it would be up to their browser's image handling to do the resizing right? I guess if you wanted to make sure it does a nice job no matter the browser, you could use php and generate a new image using gd and use that as your thumbnail. Up to you, how much work you feel like putting into it.

chronozphere
02-10-2010, 02:08 PM
Hmm.. I think the background approach is quite interesting. I'll check that out.

I did some more research and I found out that horizontal centering was simply done by using "margin: auto;" in the stylesheet. Vertical centering is alot harder. This is what I did:

http://blog.themeforest.net/tutorials/vertical-centering-with-css/

If you don't set widht/height explicity, the image will just take it's place. Also, you can use max-width/max-height on the div to restrict the space it is taking. :)