I’m trying to make a full screen slideshow kind of effect jsFiddle code here, but I am having doubts as to how to do it. As can be seen from my example fiddle, I want the picture to be as big as possible without distorting it (fit to screen). I also want it to be centred vertically and horizontally.
Horzontal centring it is taken care of in css, but I have had to use JavaScript for vertical centring.
My questions are:
- Is there a better way to do any of this (e.g. all in CSS)?
- On first load, if the picture (before it has been scaled) is wider than the viewport, a scrollbar is present while my script calculates the height of the viewport. This means that when my script fits the div and img to the window, there is a white gap at the bottom, that is the height of the scroll bar. I can get around this by specifying overflow:hidden, but it seems a bit of a work-around. Is there a better way? Would toggling the image be better?
- When I resize so that the div is wider than the image, I get a white section under the black div, which creates a vertical scrollbar. Again I can get rid of this with overflow:hidden, but I don’t like that approach. I want to know why it is there and how to get rid of it?
- Sometimes I can make a horizontal scrollbar appear and as i resize it flashes on/off. overflow:hidden fixes this, but I want a cleaner solution.
- Are there any better ways of coding this, or can my jQuery/Javascript be optimised any further?
Well… that ones tricky. The best way I’ve found how to do this is to actually put your content in a single cell table and set the vertical- and horizontal-align properties to…. middle and center I think? But anyhow, it can be done. I’ll play around with it and see if I can get an example together.
EDIT:
Ok so the first thing I would advise is to let the browser proportionately resize things. You don’t need to resize the div, just the image. You can let the browser figure out the vertical alignment as well, which is a much better option than calculating it. This can be done by placing the content in a single cell table. The example code below is pure html and css. You can add something to the effect that you already have to switch the image height and width between 100% auto and auto 100% based on img height vs window height. Hopefully this gets you a little closer to your goal.