Jump to content

How to redirect to a mobile site based on the browser’s screen width

0
  adfm's Photo
Posted Jan 25 2010 03:36 PM

If you would like to redirect mobile users to a stylesheet more suitable to viewing on a mobile device, use this excerpt from Christopher Schmitt's CSS Cookbook, Third Edition.


Detect the screen width of the current browser and redirect the browser to a more mobile-friendly version of the site’s design:

<script type= "text/javascript">

if (screen.width <= 481) {

 document.location = "http://mobi.example.com/"

 }

</script>

The base resolution relies on the Javascript being able to detect the browser width (based in pixels). If the browser width is less than or equal to 481 pixels, it’s assumed that the browser is a mobile device.

Note

Not all mobile devices have Javascript.

Higher-resolution design

You can also flip the script to detect whether a user’s browser has a larger-than-average browser window open:

<script type= "text/javascript">

if (screen.width <= 481) {

 document.location = "http://mobi.example.com/"

} <strong class="userinput"><code>else if (screen.width >= 1280) {</code></strong>

 <span class="strong"><strong>document.location = "http://high-def.example.com/";</strong></span>

<span class="strong"><strong>}</strong></span>

</script>
Cover of CSS Cookbook
Learn more about this topic from CSS Cookbook, 3rd Edition. 

Learn how to solve the real problems you face with CSS. This cookbook offers hundreds of practical examples for using CSS to format your web pages, and includes code samples you can use right away. You'll find exactly what you need, from determining which aspects of CSS meet the specific needs of your site to methods for resolving differences in the way browsers display it.

Learn More Read Now on Safari


Tags:
0 Subscribe


2 Replies

 : Jan 25 2010 10:24 PM
Not sure how this solution is considered a redirect using CSS. The title of the post would be more accurate saying it's using Javascript.

You can, in fact, detect the device width in CSS on some mobile devices. On iPhone, for example, you can use @media queries to offer different formatting for those devices. You can't, AFAIK, do a redirect using only CSS. Here's an example of an @media query:

@media all and (max-width: 320px) {
   body {
      width: 320px;
   }
}


if your HTML is semantic, using different styles via CSS and different behaviors via Javascript may be all you need to target mobile devices.
 : Jan 26 2010 08:33 AM
I see the confusion and have updated the headline to reflect this.