Center a background image in mobile safari, landscape *and* portrait (iPhone/iPad)
I have a Background image that is 1024 x 1024 pixels; the reason for these dimensions is that I want the image cover the screen in both landscape and portrait modes. The image has a small logo right in the center of it, but otherwise it is a simple gradient. I want the image always centered; in other words, the logo must always in the center of the screen, in landscape and portrait orientations. I also want the image covering the whole screen, but don't want the background image creating unnecessary scrollbars; so I don't want it to be possible to move the image by dragging it around the screen.
Here is what I have tried (and for the sake of this example I am just using a style tag in the HTML):
The issue with the code here is that the image is not centered (in portrait mode the logo shows to the right of the screen, in landscape at the bottom of the screen). It also seems that the background image becomes part of the page content so it causes scrollbars, meaning that the image can be dragged left and right.
So here are my requirements again in point form:
- background image always covers the whole screen (no white space showing)
- image always centered (so overflow evenly divided between left and right/top and bottom)
- image stays centered when iPad is rotated between landscape and portrait
- background image is fixed (cannot be moved)
- preferably a solution using just HTML and CSS (CSS3 is also fine)
Anwyone know how this can be done?
This problem might lie between the computer and the chair! ;) I will post an update when I have sorted out an issue in my UIWebview.
Ok. It is confirmed. There is nothing to see here! :) This problem was all of my own doing and the HTML that I provided actually works correctly. This went wrong because the HTML being loaded is an error screen and in trying to "fake" the error situation I caused an actual error where the UIWebview was loaded before it was ready. When I load the HTML at the correct time, then the centering suddenly works and the scrollbars dissappear. Everything 100%.
Background images have no height and width, their height and width is dependent on the parent's height and width in which they are applied to. So it is impossible for a background image to create scroll bars.
If you want the background image to resize depending on the screen size, use this:
This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here