Wednesday, September 29, 2010

Prevent Horizontal Scrolling in Your Mobile iPhone Page

When you're building a mobile page for iPhone, Android, and other smart phones, you will sometimes notice the user can pan the page to the right or left, leaving it off center and showing blank space to either side. There's an easy, two step way to prevent this.

First, add this to your header:

<meta name="viewport" content="width=device-width; initial-scale = 1.0; maximum-scale=1.0; user-scalable=no" />

Then add this to your CSS:

body {
overflow-x:hidden;
}


This will set the viewport (the windows in the browser, essentially) to the same size as the phone's screen, prevent the phone from scaling it up or down, and prevent the user from scaling it up or down.

The overflow style on the body will prevent the browser from showing anything to the left or right of the content you intend them to see.

It's simple, but fixes a frustrating problem that faces many people new to mobile design.

7 comments:

Anonymous said...

Didn't work for me. This locked the Android Browser into being neither horizontally scrollable (the goal of the exercise) nor vertically scrollable (oh no!).

JJeffryes said...

Weird.

It works correctly on all the phones we've tested it on, including Android.

Anonymous said...

@anon: I think that should be overflow-x, not overflow-y.

JJeffryes said...
This comment has been removed by the author.
JJeffryes said...

Good catch!

Typo on my part. The version we actually used had y, but we locked down the vertical too.

Anonymous said...

thanks for this!

Anonymous said...

Thanks for the tip ... before this fix I could move the page just a little, left and right on my iPhone. This is fixed but I can still drag my page left & right with the width fixed for the page but the page itself moving off-screen with a brown'ish background??

Any ideas on what might be the cause? Apple.com does not do this so I inspected their content but no insights(Opera emulator/dragon fly).

You are correct, this stuff is frustrating! Thanks again!