How to use PhoneGap API + iOS, Android

Last blog post I showed how to use PhoneGap’s API with Windows Phone 7. For this blog post, I will use the same web files (HTML and Javascript files) and create an iOS and Android application.

How to setup dev environment?
First thing to get started is visit PhoneGap’s website where they have instructions on how to setup your environment to create an iOS and Android app with PhoneGap. Just select your platform and the instructions will update update on the page for that environment.

After you have your iOS and Android environment setup using Xcode and Eclipse, copy the web files into the “www” folder for each project. Below is a screen shot of the project navigator or package explorer inside Xcode and Eclipse.

Package Explorer in Eclipse for Android Project Navigator in Xcode for iOS

Since I’m reusing the web files, all the code is exactly the same across the Android, iOS and Windows Phone 7 app. So, I’ll just show a few of the pages/screens in the iPhone simulator and Android simulator.

Device Screen (Android) Device Screen (iPhone)
Notification Screen (Android) Notification Screen (iPhone)

Click here to download the iOS example project.
Click here to download the Android example project.

How to use PhoneGap API + WP7

How to get started?

In my previous blog posts I’ve shown how to use PhoneGap with Xcode and Eclipse in targeting iOS and Android platforms. For this blog post, I will show how to use the PhoneGap API with Visual Studio and the Windows Phone 7 emulator as your development environment.

For this sample project, we will also be using JQuery and JQuery Mobile UI.

Now to get started, PhoneGap has documentation on what tools to download and what steps to follow. After you have your development environment setup, you can look over PhoneGap’s API documentation. The API is not to cumbersome and is straight-forward in following for each of the different device hardware. Most of the API involvrs javascript callbacks as I will show below in example code.

For this blog post, I will discuss how to use the following:
1. Device
2. Accelerometer
3. Camera
4. Geolocation
5. Notification

Most of the API methods and objects will exist on most of the major platforms (iOS, Android, WP7). However, some things will be specific on some platforms. Android and WP7 has a search and back button but iOS doesn’t. The menu button only exists on Android. In general, you should be able to use the PhoneGap universally on all platforms. But its good practice to test and run on each device to make sure it works they way you expect.

The sample project was developed fully in Visual Studio and tested with the Windows Phone 7 emulator. The 5 device hardware features that I will interact with using the PhoneGap API is shown on their own phone screen. The examples are very simple to explain how to use the PhoneGap API.

Below is a screen shot of the sample project’s Solution Explorer in Visual Studio. Notice the “www” folder. This folder is created with the PhoneGap project template and where all your web files (HTML, CSS, JavaScript, etc) exist.

Solution Explorer

Before we dive into the API code for each phone screen, I want to mention when using the PhoneGap API you should place your javascript code inside the javascript event OnDeviceReady. If you place your javascript code that calls the PhoneGap API in here, you can guarantee the device is loaded and ready to interact with. Below is the code included in the index.html file.

        <script type="text/javascript">

        document.addEventListener("deviceready", onDeviceReady, false);

        // once the device ready event fires, you can safely do your thing! 
        function onDeviceReady() 
        {

        }
        </script>

Now lets dive into example code.

Device – Gather device specific information

The HTML and jQuery Mobile UI for the Device screen.

<body>
    <div id="home" data-role="page">
        <div data-role="header">
            <h1>Device</h1>
            <a href="#accelerometerpage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Device API
            <!--<a href="#newpage" data-role="button">Second Page</a>
            <br/>-->
            <p id="devicename"></p>
            <p id="devicephonegap"></p>
            <p id="deviceplatform"></p>
            <p id="deviceuuid"></p>
            <p id="deviceversion"></p>
        </div>
    </div>
</body>

The jquery code inside onDeviceReady. The device object is from PhoneGap’s API and its value is added to the innerthtml for each #device element.

        <script type="text/javascript">

        document.addEventListener("deviceready", onDeviceReady, false);

        // once the device ready event fires, you can safely do your thing!
        function onDeviceReady() 
        {
            console.log("onDeviceReady. You should see this message in Visual Studio's output window.");

            $('#devicename').html(device.name);
            $('#devicephonegap').html(device.phonegap);
            $('#deviceplatform').html(device.platform);
            $('#deviceuuid').html(device.uuid);
            $('#deviceversion').html(device.version);
        }
    </script>

The HTML and jQuery Mobile UI for the Accelerometer screen.


      <div id="accelerometerpage" data-role="page">
        <div data-role="header">
            <a href="#home" data-icon="back">Back</a>
            <h1>Accelerometer</h1>
            <a id="camerabutton" href="#camerapage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Accelerometer API
            <p id="aX"></p>
            <p id="aY"></p>
            <p id="aZ"></p>
            <p id="aTime"></p>
        </div>
    </div>

The jquery code inside onDeviceReady. The navigator object is from PhoneGap’s API. Here the navigator object calls the watchAcceleration method where the first input is the success callback method, the second parameter is the error callback method and the third parameter is the frequency in millisections the success callback method will fire.

var watchId = navigator.accelerometer.watchAcceleration(onAccelSuccess, onError, { frequency: 1000 });

        function onAccelSuccess(a) {
            $('#aX').html(a.x);
            $('#aY').html(a.y);
            $('#aZ').html(a.z);
            $('#aTime').html(a.timestamp);
        }
        
        function onError() {
            // TODO: write error logic
        }

The HTML and jQuery Mobile UI for the Camera screen. Here we will write to the imageuri the fileURI of the image we capture. It will write out the location and filename of the image.

      <div id="camerapage" data-role="page">
        <div data-role="header">
            <a href="#accelerometerpage" data-icon="back">Back</a>
            <h1>Camera</h1>
            <a href="#geolocationpage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Camera API
            <p id="imageuri"></p>
        </div>
    </div>

The jquery code inside onDeviceReady. The navigator object calls camera then the getPicture method. The input parameters are similar to the Accelerometer except the third parameter where we define inline the quality, destinationType and Camera.DestinationType.FILE_URI. The file_uri that is returned in the success callback method will be added to the innerhtml at imageuri.

navigator.camera.getPicture(onCameraSuccess, onError, { quality: 50, destinationType: Camera.DestinationType.FILE_URI });

        function onCameraSuccess(fileUri) {
            $('#imageuri').html(fileUri);
        }

The HTML and jQuery Mobile UI for the Geolocation screen. Similar to the Accelerometer screen, we will write the lat/lon values to the innerhtml.

      <div id="geolocationpage" data-role="page">
        <div data-role="header">
            <a href="#camerapage" data-icon="back">Back</a>
            <h1>Geolocation</h1>
            <a href="#notificationpage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Geolocation API
            <p id="lat"></p>
            <p id="lon"></p>
        </div>
    </div>

The jquery code inside onDeviceReady. Here we’re calling the watchPosition of geolocation object and on the success callback method retrieving the lat and lon values.

navigator.geolocation.watchPosition(onGeolocationSuccess, onError, { frequency: 1000 });

        function onGeolocationSuccess(p) {
            $('#lat').html(p.coords.latitude);
            $('#lon').html(p.coords.longitude);
        }

The HTML and jQuery Mobile UI for the Geolocation screen. Here we created an anchor tag that will look like a mobile button that will display a PhoneGap notification alert.


      <div id="notificationpage" data-role="page">
        <div data-role="header">
            <a href="#geolocationpage" data-icon="back">Back</a>
            <h1>Notification</h1>
            <a href="#storagepage" data-icon="add">Next</a>
        </div>
        <div data-role="content">
            PhoneGap Notification API
            <br/>
            <a id="notificationbutton" href="" data-role="button">Click Me!</a>
        </div>
    </div>

The jquery code inside onDeviceReady. Here we use jquery to create a handler for notificationbutton that will call PhoneGap’s API object navigator.notification.alert. When the success callback method is reached it will update the innerhtml text of the button to Clicked.

            $('#notificationbutton').click( function() {
                navigator.notification.alert("You clicked me!", onNotificationSuccess, "Click", "Ok");
            });

        function onNotificationSuccess()
        {
            $('#notificationbutton').html('Clicked');
        }

I hope this helps in getting started with PhoneGap’s API. There is a lot more that can be discussed.

Here is the code for the sample project.

Font Hybridization in HTML 5

Over this Christmas break, I was over at a friends house and got to sit down and tinker with my friends Mac. I’d forgotten how good fonts look, and I suddenly realized why so many sites are now using custom web fonts. Since I primarily use Windows at work and at home, I get annoyed by fonts that are difficult to read or that don’t render well on the screen. Somehow, I’ve never been 100% happy with font rendering on windows. It’s been getting better, but it’s still not as good as a Mac is. Maybe its the screen, maybe its the OS, maybe its the app, maybe its a combination of all of the above. Because I’ve been on this HTML kick, and I’m on windows, I’ve tended toward Cufon as my font replacement tool of choice when building sites since it’s the only one that produces a “more-reasonable” output on my machine.

But Cufon by it’s nature has several drawbacks. First, you can’t copy and paste text rendered with Cufon. With most of the newer browsers you can select it, but there’s not much more you can do beyond that. So, I usually limit Cufon usage to titles, headers, and the more “design-ery” aspects of a page. Second, because Cufon is image based, if someone zooms in on your text beyond 100% Cufon rendered text gets all fuzzy the same way it would if you zoomed in on an image. And finally, because Cufon renders with javascript on the client, there’s no way to cache the text. Javascript is fast, but when you’re rendering a large amount of text on a phone, there’s usually not a good way around a flash of unstyled content. And it happens each time you go to a new page because it can’t be cached.

Web fonts on the other hand, allow you to use fonts in a very similar manner as if you had them installed on your device with native rendering by the OS. You can select, copy, paste, and use it as you would any other piece of text. Web fonts are cacheable, so although you could get a flash of unstyled content when you first visit a page, subsequent visits should render immediately. The disadvantage however, is the OS. On windows, the rendering of fonts just… Sucks. So people don’t use it.

But what if there was a way to do a hybrid between Cufon and Web Fonts?

Besides the rendering issue, Web Fonts are the best option. They’re the most flexible and the most future proof. But they still suffer on Windows, some phones, and on older browsers that don’t support the new @font-face CSS syntax. So what if we did a hybrid? Use @font-face, then fall back on Cufon for older browsers, and for windows. The advantage is that on a new browser the@font-face‘s will be cached, used for the initial rendering of the page, and then cleaned up with Cufon later.

Using Modernizr and a little custom javascript to do user agent testing I put together a page to test out the hybrid font idea:

http://www.paulrohde.com/demo/cufon-hybrid/demo.html

It’s a rough draft. I have some screen shots below from both Mac and PC’s (click for full size versions).

Mac

PC

For simplicity, the javascript code to test and load Cufon and my custom cufon polyfill looks like this:

function rendersNiceFontface() {
	result = navigator.appVersion.indexOf("Win") != -1 
		|| navigator.appVersion.indexOf("Android") != -1;
	return result;
}

var supportsNiceFontface = !rendersNiceFontface();

Modernizr.load([
	{
		test : Modernizr.fontface && Modernizr.canvas && supportsNiceFontface,
		
		nope : [ 'cufon-yui.js', 'BebasNeueRegular_400.font.js', 'cufon-polyfill.js' ]
	}
])

Using the Modernizr yepnope.js, I’m able to completely skip loading Cufon at all if the browser supports good @font-face rules. There’s more that I’d have to do to clean it up before I’d use it in a real setting, but it demonstrate the concept, and is something I could definitely use later as a @font-face polyfill. It does have some drawbacks though, you have to maintain both your CSS rules and your Cufon replacement calls, and Cufon doesn’t work well with a large amount of body text, so if you don’t support @font-face, I’d fall back to a good secondary font and forgo Cufon in those cases.

I hope this got some gears turning, I’m looking forward to some comments.

CSS Is A Lie.

According to Wikipedia:

Cascading Style Sheets (CSS) is a style sheet language used to describe the presentation semantics (the look and formatting) of a document written in a markup language.

Furthermore:

CSS specifies a priority scheme to determine which style rules apply if more than one rule matches against a particular element. In this so-called cascade, priorities or weights are calculated and assigned to rules, so that the results are predictable.

From my informal office survey, the general consensus is that the most important thing™ in CSS is that everything ‘cascades’ correctly. That is, that rules and styles defined further down in a CSS document override styles specified further up in the document (excluding the !important operator of course, which you should not be using anyways). It makes sense if you think about it, after all it’s not called a Cascading Style Sheet for nothing.

Now, the test. Given the following HTML and CSS snippet, what color will the two paragraphs be?

HTML

<p id="myid" class="myclass">
   Hello World.
</p>

<p class="myclass">
   This is another line of text
</p>

CSS

#myid {
   color: red;
}

.myclass {
   color: blue;
}

p {
   color: green;
}

The Answer:
Hello World is red, the second line of text is blue.

Don’t believe me? I put up a demo page with just the html and css here.

After a decent amount of Googling and reading blogs and the W3C Spec on CSS Selectors, I realize now how styles are calculated and applied, but seems to go completely against the ‘cascading’ nature of style sheets since the cascading nature of style sheets only applies when the ‘specificity’ values are the same.

For example, the following snippet behaves as you would expect:

CSS

p {
   color: gray;
   font-size: 20px;
}

/* ... later ... */

p {
   color: green;
}

As you might expect the paragraph will be green, and have a font size of 20px. The rule that is more specific selectors takes precedence over rules that are less specific regardless of where that rule is declared in the markup. You can mentally calculate how specific a rule by the ‘level’ and number of the selectors used. From low to high, you have

  1. Element and pseudo elements such as p, a, span, div, :first-line
  2. Class, attributes, pseudo-classes .myclass
  3. Id attributes #myelement #theonething
  4. From inline style attributes
  5. !important

If there’s anything of a higher level, the higher level overrides the lower level style, and if they’re the same level, the higher count wins, and if they’re at the same level with the same count (.myclass, and .myotherclass) then the one further down takes precedence, this is the “only” time cascading actually happens.

Its something that is unfortunately very subtle because of the way we write CSS, your taught from the begin to start with the most basic generic styles and work your way through the more specific styles. While this is correct, it’s very easy to go for a long time without running into a situation where a more specific styles.

I had no idea up until about a week ago that CSS worked like this. I always assumed that specificity was only used to select the subset of elements the rule applied to, and that if you applied a more general rule after a more specific rule that the more general rule would overwrite anything earlier. This is obviously not the case. If you want to read more, here’s some links to a few more comprehensive articles on the subject:

CSS Specificity and Inheritance: http://coding.smashingmagazine.com/2010/04/07/css-specificity-and-inheritance/

Star Wars and CSS Specificity: http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html

Specifics on CSS Specificity: http://css-tricks.com/855-specifics-on-css-specificity/

Art and Zen of CSS: http://donttrustthisguy.com/2010/03/07/the-art-and-zen-of-writing-css/

Designing For Code: Copy & Paste

As a developer, I’m constantly on the web. Learning, reading, finding solutions to problems or looking up odd bugs. There is a great community of developers that are constantly publishing solutions / fixes / workarounds / techniques for the benefit of their fellow developers. Being developers, you would expect to find that the sites they run are easy to use across the board! For the most part they are but every now and again though I run across a site that makes me want to bash my head against the monitor. Why? Because it breaks the simplest feature:

Copy. Paste.

If you EVER post code on the web on a site you control, or if you are in charge of a site where you or others post code. Make. Sure. Copy. Paste. Works. Period. I’m not just talking about ‘I can select it and paste it’ functionality, I’m referring to those ‘code highlighting’ plug ins that add line numbers to EVERY SINGLE LINE of a code snippet when you paste.

Don’t Do It.

There are lots of good highlighting plug ins out there, sites that will format your code for you, and so on. Whatever method you chose, test it and make sure you can use the code from your site without having to modify or do anything to it. If you can’t, abandon it. Find something else. Use raw text. Whatever it takes to get the basics working well.

In addition, make sure your code works well when the site is scaled up or down. If you have a site that doesn’t change width as the browser size changes, ignore this, and read this post on fluid layouts: http://blogs.interknowlogy.com/2011/10/25/on-modern-layo…mi-fluid-grids/. Now IF your site changes width, your code should ALWAYS work on whatever size the visitor is looking at the site on. Check it on a smart phone. Check it on a tablet. Stretch your site across two wide screen monitors. If it ‘breaks’ (as in becomes unreadable or inaccessible) fix it. Go back to the basics. Remove / alter / don’t use a plugin. Again, do whatever it takes to make the basics work.

Don’t underestimate the importance of the small supposedly insignificant details. In all honesty, users aren’t going to come to your site and praise you for what an elegant job you did on making your code easy to copy and paste, or how nice the content looks, or how readable the article is. Its similar to the way people will notice spelling and grammar. If your sentences are well formed and correct and the article is well structured the person reading should never have to mentally think about it. On the other hand, if an article is not well crafted, that person will have to wade through the mistakes and mentally jump between what was actually written and what the author intended. In same way, whatever type of content you present to a visitor, it should always be presented it in such a way that the person consuming it can do so without ANYTHING getting in the way of them doing so effectively.

Think about it. Go check your site. Make the net a better place.

Invisible extra line height

I came across this annoying off by one pixel layout issue several days ago when dealing with <code> tags. You may not even guess that its caused by it at first, but if you ever try to test your layout with a baseline script, you may notice this.

Take a good look at the following screenshot and tell me, are these two paragraphs the same height?

The correct answer is No. They’re not. If you look at the line height, the font size, almost everything you’ll find that these two paragraphs are exactly the same with the exception of the <code> tags in the second paragraph. Digging in deeper you’ll see the following problems with the paragraph height:


Four. Pixels. Taller. *explicitive*. Most people wouldn’t care, or even notice unless you were using a baselineing tool like Typesetter. The solution, after much digging around, is to set the line height of <code> tags to zero.

code {
     line-height: 0;
}

And like magic, all of a sudden your paragraphs now behave correctly. This may be classified as a bug, at the very least, its an annoyance, but if you find yourself having problems with your paragraph line heights not behaving quite right, take a look and give this a shot.

Typesetter HD

Just a quick heads up, I updated TypeSetter to work with high density displays. So if your on an iPhone 4 or 4S, or any other device that has a non standard pixel ratio and uses the baseline script it will show up clean and sharp.

http://gist.github.com/1270673#file_type_setter.js

Here’s a sample with the updated grid drawing code:

Back to HTML – Tricky margins

HTML layout is weird. Half the time it makes sense, and the other half it makes half as much sense as it should. To that end, here’s a quick refresher on margins and padding and layout that I’m writing as much for myself as for you.
Lets start with a box. In this imaginary real box wold, you are either putting blocks next to each other, or inside other boxes, to get elements to line up and appear in some fashion or another. These virtual boxes have two properties, margin and padding. In our box world analogy, the padding would represent the thickness of the walls of the box. If you add something thats bigger than the inside of the box, the actual outside edge of the box will have too expand to contain whatever is inside. When you set a margin however, its simply stating a rule that you would like this box to be at least x number of units away from any other sibling box.

For instance, I have Box A and I want anything around Box A to be at least 2 feet away on the top or bottom of the box. Now, I have Box B that also has margin, but for Box B I only need everything to be 1 foot away along the top or bottom of the box. If I placed these two boxes next to each other (as siblings), the boxes would be 2 feet apart. Box A overrules Box B since A requests any other box to be further away from B, and thus B is also satisfied since the margin for B is less than A. If I also specified padding for box B of 6 inches, the contents of B would be at least 2 feet 6 inches from A since margin is measured from the outside edge of the box.

Here is a real example. In this case, I have 2 paragraphs. The orange space represents margins, and the green represents padding as shown by the debugging tools in chrome.

The code looks something like this:

<article>
     <p>This is some paragraph text 1</p>
     <p>more paragraph text</p>
</article>

Example 1 Margining:


Notice how the margins collapse when they touch each other. Remember that margin represents ‘minimum spacing’.

Example 2 Padding:


Notice how not only are the paragraphs further apart with similar spacing, but they padding doesn’t overlap at all. This distinction is important when you lay out content, and especially when you start floating things. Eventually the imaginary real box model starts to break down as we approach real world HTML. Another really important tidbit to understand is that margining can extend OUTSIDE of the container. For instance, in the previous code snippet, we only have one article and two

tags. If we put two articles side by side, we can see how the paragraph margining will extend out of the article block:

HTML:

<article>
     <p>This is some paragraph text 1</p>
     <p>more paragraph text</p>
</article>
<article>
     <p>This is some paragraph text 1</p>
     <p>more paragraph text</p>
</article>

Note how the article is only the size of the paragraphs inner dimensions:

However, when we look at the paragraph margining, we see:

The paragraph spacing extends beyond the bounds of the article and pushes the paragraphs and the article down. I know. The box model doesn’t work any more. Remember the differences and play around with it yourself.

Some Practical Advice

  • When you first start laying elements out on a page, only specify bottom margining and keep the space consistent. It will help debug initial issues since there will be less overlapping margins.
  • Use a sylesheet language like less or sass so you can keep the numbers more consistent and easier to change.
  • Use good debugging tools. Chrome Developer tools, or Firebug are both good. They’ll keep you from going insane immediately.
  • If all else fails, simplify the problem. Make a small, quick html page to try to replicate your scenario.
  • Tinker. You only learn something by doing it. Do it.

Tip: Using zoom to target images to high density displays

I found this several days ago when I was looking for a way to scale images on an iPhone inside of a fluid layout such that they would display at a 1:1 pixel ratio. If you didn’t already know, the iPhone 4 and 4S displays everything as if the screen was the same size as a normal iPhone when it measures and does the layout. The result is that all the text looks extremely crisp, and any sites already designed for the original iPhone don’t break or look weird. With images this means that a 300 x 300 pixel image displays the correct size in the layout, but is essentially scaled up to fit over 600×600 “physical pixels”. As I was poking around I found an old CSS zoom property here: http://reference.sitepoint.com/css/zoom that for some reason works on mobile safari. Add a media query for 2x density screens, and viola! Your images now display at physical pixel dimensions on the iPhone 4 and 4S.

Here’s what the CSS looks like:

@media screen and (-webkit-min-device-pixel-ratio: 2) {
     img {
          zoom: 50%;
     }
}

Awesome hacks.

Happy img scaling.

On Modern Layouts and Semi Fluid Grids

Over the last several weeks, I’ve really been digging into HTML5, CSS3, and really figuring out what modern browsers can do. Frankly browsers have grown by leaps and bounds over the last several years, and as such we need to re-evaluate how we build websites. Especially in regards to how we treat older browsers. I recently read this post by Paul Irish and he points out that ideally, each browser gets an experience that is customized to that browser’s capabilities. What this means however, is that we should expect older browsers to get an experience that isn’t exactly the same as the experience we get on a modern one. (Example, no rounded corners. No text shadows. Etc…)

Let me try to explain:

A really good analogy to this is how HD TVs have changed the TV industry. Imagine for a moment that a website site is the film, and the TV is your browser. If you had a black and white TV, you wouldn’t expect to see the film in color. If you have a standard definition TV you don’t expect to see the full wide screen movies, and if you have a widescreen 720p TV, you don’t expect to experience the full effect of 1080p Blu-ray. Filmmakers don’t shoot in standard definition and then try to ‘upgrade’ the film to HD quality. Its pointless and a LOT of extra work. No, they shoot with the best film and resolution they can afford and then cut it down to the lower denominators when or if they support older formats.

In the same way, if you use an older browser you wouldn’t expect to get the full experience a modern browser supplies, and moreover, you likely wouldn’t even know what your missing! You don’t expect it since any other site you visit also doesn’t have those features or details. Because of this, you should be designing for the ‘1080p’ of the web, and accept that users with older browsers will still get the ‘standard definition’ experience.

The Web Is Not Print

There’s also an important distinction between print and the web. The web is dynamic and fluid, highly interactive. The web is also delivered on a range of sizes and devices, from something the size of a business card up to large 30″ monitors. There comes a point where form and function have to merge in a non-trivial way to provide an experience that fits itself to the users needs, when they need it, the way they need it.

Print isn’t.

Print is extremely static, once it’s designed, it stays that way. If you design a poster, you design it to be printed at a certain size or at certain proportions. If you design a book or a magazine, you have total control over the size and layout of your spread. If you continue to think about the web this way, you’ll miss much of the dynamic nature of the web that makes it attractive as a medium.

Its only recently we’ve really gained the tools and techniques we need to REALLY break out and away from the classic printers layout due largely to the rise in mobile devices, HTML5 and CSS3. What I’m calling this “Print Format” tends to reveal itself at the extreme edge cases.

Specifically:

  • On large monitors where content will appear tiny and hard to read with lots of extra white space.
  • On small monitors or mobile devices when the content doesn’t scale down and your forced to scroll back and forth to read.

Over the years one of the only real solutions to address this, if someone addressed it at all, was just to never set a width for your content and just let it fill your entire screen. Although this almost works for some things, it’s difficult to read as paragraphs will stretch across the screen. You will constantly lose your place as your eyes track back and forth to the beginning of the next line. Also, if your designing a static site and you and your designers both have large screens, it’s easy to ‘fill up the space’ with ancillary or useless content and ads to make the site feel balanced. All in all, most so called solutions were hacks on a broken system.

Semi Fluid Layout

I’m finally starting to see some CSS frameworks and sites that are really starting to apply these principles. An excellent site that demonstrates this principle is the following:

www.goldengridsystem.com

No matter what browser you visit it on, or what size your browser is at, the content will be sized appropriately, the typography will be readable, and everything will feel right. Sans insane urges to resize your browser window.

One of the key benefits to designing a fluid theme is the instantly correct look you get when you open the site. Its not something people will or should consciously expect, it should simply BE the correct size the instant it appears, regardless of size, screen, or orientation. Its like walking into a store. A well designed building is easy to navigate, spacious, and consistent across all other stores you visit regardless of size. You don’t ever think about it, you’re not there to analyze the layout of the store. You’re there to buy groceries. Anything that gets in the way or makes it hard to find what you’re looking for will stick out, and if it’s bad enough, you’ll go somewhere else. Its the same way with a site or blog. Users are there for a reason: For information, or to read, or to consume whatever content you are serving up. They didn’t come to analyze your site and how it’s designed, but if they have any difficulty at all in getting to what they want in whatever form they want it in, they’ll be somewhere else in about 8 seconds.

It’s also important to be intentional about the decisions your making and how they will affect the final layout of a site. The more you reduce the complexity of the interactions, and the better defined the interactions are, the better the final end result will be. Use what you design. Do what your users do. You’ll know best what you do and don’t like and what feels right. Go with it, but don’t be afraid to stop, backtrack, or even completely scrap good ideas if they don’t fit with what you expect from the design.

Fluid Layout First

Something that’s going to become really important is to start out your design efforts knowing your designing for a fluid site like this. Laying out the groundwork and page structure is going to be extremely important to your long term sanity as a developer. There’s this concept in computer science called emergent behavior, essentially, the less you specify about a system, and by imposing fairly simple rules you can get easily get complex behavior. By starting with the containers, and then working your way to the content I have much less to worry about since most of the content takes care of itself without much more intervention from the developer.

If your someone who already has a well established, static width layout, its going to be difficult to establish a well behaved fluid grid system without tweaking MANY aspects of the site. Its probably why a lot of companies simply serve up an entirely different set of HTML and CSS for the site for mobile devices: Its easier to do than to rebuild their main site to scale all the way down to small screens.