Andy
Andy

Reputation: 1432

correctly scaling website to display in iphone

I built a mobile website to fit 320px wide. In this thread (http://stackoverflow.com/questions/4520064/mobile-website-for-iphone-problems) it throws out a useful piece of code to ensure that the iPhone displays it at the correct resolution, 320 wide. However, when I rotate the phone it doesn't automatically rescale to fit the wider viewport.

Any suggestions on how to fix that?

Upvotes: 1

Views: 536

Answers (3)

David Nguyen
David Nguyen

Reputation: 8528

Hard to tell with out seeing the site but I'm gonna take a stab: your explicitly saying the website width is 320px, when you rotate it the width of the phone isn't such. Your wrapper should be width: 100% so that the document rescales it self or you rescale the viewport.

Upvotes: 2

Moses
Moses

Reputation: 9173

You can dynamically size your content using CSS media queries [w3.org].

To detect when a mobile phone is portrait or landscape, use orientation, for instance:

@media all and (orientation:landscape) {
    /* apply your css styles here */
}

You can also chain together specific scenarios, depending on how specific you want to be. For instance, if you wanted to style a portrait browser with a device width of 400px you would do the following:

@media all and (orientation:landscape) and (device-width:400px) {
    /* apply your css styles here */
}

*It should be noted that media queries should be at the very end of your CSS files, otherwise they won't properly overwrite your existing styles.

Upvotes: 3

tamarintech
tamarintech

Reputation: 1982

For some of my mobile projects, I have been using an event listener for the resize event. When the device shifts from portrait/landscape (or the desktop window resized) the event will be called and you can manually set the height and width of your elements.

Here is an short example of what I have been using:

window.addEventListener('resize', resizetick, false);
<...>
function resizetick(e) {
    if(this.resizet)
        clearTimeout(this.resizet);
        resizet = setTimeout(resizecallback, 100);
}
<...>
function resizecallback() {
    <if new resolution then resize elements here>
}

The purpose behind the setTimeout/clearTimeout is to prevent multiple resizes. Desktop browser events are fired continually while resizing and mobile users may shift the direction of their device inadvertently. I want to avoid resizing the content repeatedly.

You'll need to bind or otherwise handle resize() and resizecallback(). I don't have a project handy to cut and paste working code from - sorry. :\

Upvotes: 2

Related Questions