I’ve tried many different things but none is working.
I have a picture (let say unknown height and width) and I want it centered (vertically and horizontally). The height and width is determined by the window size, but must not be more than the original height and/or width.
As an exemple, you can look at Windows Live Photo Gallery, when you double click on a picture. This is exactly what I need, in css/jquery. I don’t know how to adjust the image to fit as I want in the page.
Thanks for any help.
I don’t know the specific term since english is not my native language.
If you know your image’s size before hand (on the server side), the easiest way is to do it when rendering the HTML; use the
widthandheightattribute of your<img>tag to set its size, and it’smargin-leftandmargin-topto center it into a container. This will make it a lot better for the end user as he won’t see the screen flicker when re-sized javascript side after the image is loaded. This is by far the best way to do this.Edit: as stated in the comments, if you use the server side solution you might want to still use a javascript solution on $(window).resize(), so that the image stays centered and properly sized if the user change the window’s dimensions.
—
However, since your question is for javascript, you need to work in two steps; first reduce the image height and width so as not to be larger than the window while keeping ratio, then in a second time apply some margin to center it both horizontally and vertically.
Here is an example of how you could achieve what you want, note that this code is clearly not optimized and probably shouldn’t be used as-is, I leave it in its “verbose” way to keep it easier to understand.
The HTML:
The JS:
You can see it in example here: http://jsfiddle.net/RPCjE/2/ (chome img.onload event is quite buggy so if you are using this browser you might have to refresh with no cache).