Mobile CSS Isn’t Easy

I’ve had an iOS device for ages now, by today’s standards it’s a dinosaur, but it is useful for a few things besides as an ebook reader — testing my sites with a mobile device. For awhile I’ve just ignored my personal site as the main area you could zoom-in on pretty easily and it was “readable” for the most part… However today I decided to go a step further and target mobile users specifically.

Anyone who tells you it’s “easy” to target mobile users probably hasn’t had to do so after the fact. As far as I can figure most people who talk about mobile CSS stylesheets expect you to be thinking about mobile devices before you even open your coding program of choice. I spent a long time reading up on how to target handheld/mobile devices with CSS; either with media=”handheld” orĀ media=”only screen and (max-device-width: 480px) inside your header, or using @media inside your main CSS file.

Ok, no thanks. I didn’t really want to, but I decided to utilize PHP to determine a visitor’s user-agent string, and from there serve them a different CSS file. Why? Because I didn’t want to “reset” my CSS for my mobile stylesheet before I even get to the mobile stuff. I utilized Mobile Detect, which is a small PHP script that looks at a user’s agent string so you can then target them specifically. Truthfully you could do a lot with this, but I needed it for something simple, if it detects a mobile user serve mobile.css, else serve style.css.

For anyone interested this is how I enabled the script, in my template’s header.php:

<?php include("Mobile_Detect.php"); $detect = new Mobile_Detect(); ?>

That should go at the top of the file. The following is where I use a PHP IF/ELSE to switch CSS:

<link rel="stylesheet" type="text/css" href="<?php bloginfo('stylesheet_directory') ?>/<?php if ($detect->isMobile()) {echo "mobile";} else {echo "style";} ?>.css" />

If you’re on a PC you’ll get the following:

<link rel="stylesheet" type="text/css" href="http://www.kupatrix.com/wp-content/themes/kupatrix/style.css" />

If you’re on a mobile device, you’ll get:

<link rel="stylesheet" type="text/css" href="http://www.kupatrix.com/wp-content/themes/kupatrix/mobile.css" />

Why did I do it this way? Well this way I don’t have to redo, reset, or otherwise do anything with the markup of my site, and my mobile stylesheet can remain small in size. What I did for my mobile site is to hide most everything, do some trickery with my header to show a smaller image (that isn’t random!) and then focus on my content.

Now if only I would get some comments working, so everyone can tell me how wrong I am or how I could do it better! How do you target mobile browsers? Do you serve a completely different theme? Do you use the WordPress Touch/Mobile plugin(s)? If you have to tell me how wrong I am, please feel free to email me: kupatrix@gmail.com

Comments are closed.