Custom-designed <select> menus without a wrapper <div>

Most of the time I tell clients we can’t customize the appearance of <select> menus (a.k.a. “dropdowns”), along with checkboxes and radio buttons. I lay out a whole rationale on the part of OS and browser developers for why these elements can’t be customized, which is perhaps marginally factual. I do think these elements are, by intention, difficult to customize, in order to avoid confusing users. But designers want to design and, to be honest, the browser defaults for these elements are pretty freaking ugly.

Often there are complicating factors that really do make it effectively impossible to customize these elements. And so far I have not found any way to customize radio buttons and checkboxes that don’t involve “faking” them with images and hidden inputs. Solutions that may achieve the desired appearance but that are oh so ugly on the inside.

I’ll also admit that I am usually the developer on a project, not the designer. But at the moment I am working on a project where, OK, I’m still not the designer, but I have taken responsibility for extending the design, which affords/requires of me making some design decisions. And when I’m the one designing things, I care a lot more about finding a way to make them look exactly like what I’ve envisioned.

So, we come to <select> menus. While it’s not really possible to do much with radio buttons and checkboxes, there at least are some CSS properties that these menus will take. Unfortunately they vary a lot between browsers and don’t solve every problem.

Most solutions I’ve seen for modifying the appearance of <select> menus involve wrapping the menu in a container <div> or <span> tag, essentially removing all of the CSS properties from the menu element itself, and then styling the container as desired.

I hate this solution. I want to be able to style the <select> itself, and be done with it. And at last I have found a solution that mostly accomplishes this, with the caveat that it does not work in Internet Explorer before version 10. But I have a fallback for IE 9 and earlier that does almost everything. And I haven’t tested in Opera because… come on. (OK, I’ve heard Opera is popular in Europe, but to be honest all of my clients are in the United States and do not do business in Europe, so it doesn’t matter. No one I have dealt with has ever cared if their site worked in Opera. Or probably even known it exists.) I should also probably just note that my company no longer supports Internet Explorer 7 or earlier, so we’re only concerning ourselves here with making sure it at least looks OK in IE 8.

OK, so how does this work?

Pretty much every browser supports some basic customizations of the <select> menu with CSS, like changing the background color, font, text color, size, etc. But there’s extra browser “appearance” junk we need to get rid of. Mostly the little up/down arrow at the right end of the menu that is the visual cue to users that it is a menu. That’s an important thing… we need to still provide some visual cue that it’s a menu. But I want to make it look the way I want to make it look.

Let’s start by getting rid of the browser junk.

select {
  -moz-appearance: none;
  -webkit-appearance: none;
  appearance: none;
}

That removes all of the standard browser styling from Mozilla (Firefox) and WebKit (Chrome and Safari). I’m not sure we really need appearance or if it actually does anything in any known browser, but I saw it in an example somewhere and I hate using vendor prefixes without also including the non-prefixed version of the same property, so there it is.

So that covers three of the four major browsers. But what about Internet Explorer? There’s a tidy solution that works in IE 10 and later:

select::-ms-expand {
  display: none;
}

Now we have a <select> menu with none of the standard browser junk, and we can apply our styles as needed. As for Internet Explorer 9 and earlier, you’ll just have to live with the arrow thing at the right end of the menu. I’ll explain in a bit the way to add separate styles just for those earlier versions of IE, using conditional comments, in case you’re not familiar.

I do recommend designing your own “arrow thingy” icon for the right side of the menu, so users can still tell it’s a menu. Here’s an example of how your full <select> CSS might look. (This is fairly close to what I am using in the site I’m actually working on, although the colors, fonts and padding differ slightly.)

select {
  -moz-appearance: none;
  -webkit-appearance: none;
  appearance: none;
  background: rgb(238,238,238) url('images/select.png') right 5px center no-repeat;
  background-size: 9px 15px;
  border: 1px solid rgb(221,221,221);
  border-radius: 0;
  color: rgb(34,34,34);
  font-family: ‘Proxima Nova’, sans-serif;
  font-size: 100%;
  height: 2em;
  line-height: 2em;
  min-width: 60%;
  padding: 0 25px 0 10px;
  width: auto;
}
select::-ms-expand {
  display: none;
}

Here’s what the results look like in different browsers.

custom_select_browser_samples

So, there’s an issue with the text alignment in Internet Explorer. As of this writing I’m working on resolving that. There are also some more minor variations between browsers in size and alignment, but that’s the nature of this business. Firefox also antialiases differently than Chrome and Safari, and I (usually) don’t bother trying to compensate for that. (The significant size difference in the IE sample is due to scaling at different breakpoints in my responsive layout… just a side effect of how I took the screenshots.)

That just leaves IE 9 and earlier. As I said, there’s no equivalent to select::-ms-expand before IE 10, so while we can change many aspects of the appearance of the menu, we can’t get rid of the standard arrow button thing. Unfortunately, if we implement the code above, we end up with both our custom arrows and the default ones, side-by-side. The only solution here is to get rid of ours, and remove the extra padding we gave it. This is where conditional comments come in. They’re well named: conditionals within HTML comments, recognized only by Internet Explorer. You can even target specific versions of IE with them. In this case, we just need to target versions before 10.

One common convention for conditional comments has you wrap the <html> tag itself in them, applying a class (e.g. ie8 that can then be used throughout your HTML everywhere else to target that browser. That’s great, but I never use it myself because I’ve gotten to a point where I rarely need to write any IE-specific CSS. So I just use the conditionals to load a separate ie.css file when I need it.

Here’s an example of how this might look. It should go in your <head> section, after you’ve included the main CSS file:

<!–[if lt IE 10]>
  <link rel="stylesheet" type="text/css" href="css/ie.css" />
<![endif]–>

And then in your ie.css file, you’ll need to override the background and padding:

select {
  background-image: none;
  padding-right: 0;
}

…and this is what it looks like in IE9 (and, just for fun, IE8 as well):

custom_select_browser_samples_ie

Obviously my styles are extremely basic — not really that different from what older versions of IE show anyway — but this does the job. As a test, I made the background bright red to prove it worked across the board. It does. But the results made my eyeballs bleed, so I’ll spare you.

But here’s something fun… how it looks on an iPhone with high resolution.

custom_select_browser_samples_ios

The arrow graphic is replaced with a high-res version using CSS3 media queries.

@media only screen and (-moz-min-device-pixel-ratio: 1.5),
  only screen and (-o-min-device-pixel-ratio: 3/2),
  only screen and (-webkit-min-device-pixel-ratio: 1.5),
  only screen and (min-devicepixel-ratio: 1.5),
  only screen and (min-resolution: 1.5dppx)
{
  select { background-image: url('images/select_x2.png'); }
}

(Yes, there’s an Opera vendor prefix in there. Forget about what I said earlier. Or not. This is just a standard block of code I always use for high-res images in my media queries.)

Depending on the complexity of your design, this approach may not offer quite as much control as you need, compared to the <div> wrapper approach, but if you’re just trying to get something clean and simple, with customized colors and fonts and without the outdated 3D styles most browsers stick you with, this should do the trick.

Some problems just never go away… especially where CSS3 multi-columns are concerned

Note: This post has been updated.

I don’t use CSS3 multi-columns (based around the column-count and column-gap properties) very much, mainly because a) I don’t need columns in my layouts very often and b) usually when I do need columns, this method is inadequately flexible for what I’m trying to accomplish.

Today I have a good use case though. A simple (but long) list of links, that I want to display as 3 columns on wide screens, 2 columns on tablets and a single column on phones. Great, except when I got it working, I found that — in Chrome only, which is a bit odd — the top of the first column is higher than the rest. It looks fine in Safari and Firefox.

I googled, as always, for a solution, and found several suggestions that seemed like they should work, and people claimed they did work, but for me, they didn’t. Then I found this comment on a post on the topic, and decided to try the column-break-inside property, which is something I normally only use in print CSS.

It still didn’t work. But then, vendor prefix to the rescue! I needed the -webkit prefix, and it worked. This needs to be applied to the elements inside your column container, not the container itself. Here’s my full CSS block:

.columns {
  -moz-column-count: 3;
  -webkit-column-count: 3;
  column-count: 3;
  -moz-column-gap: 3em;
  -webkit-column-gap: 3em;
  column-gap: 3em;
}

/* Fix for unbalanced top alignment in Chrome */
.columns > * {
  -webkit-column-break-inside: avoid;
  column-break-inside: avoid;
}

You’ll also want to repeat the .columns section (or its equivalent for your class/element names) in your media queries, changing column-count appropriately where you want to collapse down to fewer columns.

Since other solutions worked for other people, I’m guessing my solution might not work for everyone either. But I hope it helps someone… maybe you!

Update (6/28/2017)

This problem really does never go away. And I’ve just run into a situation where the above fix doesn’t work. This is only affecting Safari — I think Chrome has actually fixed the bug. But some trial and error led to this new solution that fixes the problem in Safari as well.

/* New fix for Safari */
.columns > * {
  display: inline-block;
  width: 100%;
}

I’m still not totally sure why display: inline-block; is the magic bullet for column alignment issues, but it works. Adding width: 100%; is what keeps these inline blocks from actually appearing on the same line, if they’re short enough. (Also note that I removed the column-break-inside stuff… don’t seem to need it with this change.)

Update (6/12/2020)

Wow… it really never goes away, does it?

Now I’ve found that if I am applying my .columns class to a <ul> tag, its <li> tags lose their bullets, because they apparently need to have display: list-item (or have it implied). When did display: list-item get added to the CSS spec anyway? I’d swear it didn’t even exist when I was first working on this issue, but I’m an old fart now and time has lost all meaning.

Anyway… I did manage to figure out a workaround to this. So add the following after the update above (which you’ll still keep):

/* New fix for Safari */
.columns > li {
  display: list-item;
  margin: 0 !important; /* Maybe you won’t need !important */
  padding-bottom: 0.5em; /* Add some padding to make up for any margin you’re losing above */
}

Responsive images with srcset in WordPress

As a developer, I am somewhat conservative. I believe strongly in the importance of web standards, and I am reluctant to be an early adopter of any new techniques or, even worse, non-standard workarounds for limitations in existing standards. I’d rather live with the limitations until a proper standard — or at least a de facto standard — takes hold.

One of the latest issues to challenge my approach has been responsive images. I’ve settled into a pattern of going with “1.5x” quality images, trying to strike a balance between quality on large high-res displays and a reasonable file size. But it really doesn’t do either very well.

Today’s issue of A List Apart features an exciting article:

Responsive Images in Practice

Yes! In practice! Let’s do this!

There have been a couple of competing proposals for handling responsive image sets, and I am pleased to see the srcset attribute begin to emerge as the winner. The biggest plus it has for me is that it degrades gracefully for older browsers that don’t support it.

Well, before I had even finished reading the article I started thinking about how I could leverage the build-in image sizing mechanism in WordPress to use srcset. I haven’t looked around — I’m sure someone else has already created a plugin that perfectly nails what I am attempting to do here. And, to be honest, I haven’t extensively tested this code yet, although I did drop it into a site I’m currently working on, just to be sure it doesn’t throw a fatal error and that it actually does render the HTML <img> tag as advertised.

function img_with_srcset($attachment_id, $default_size='medium', $echo=true) {
  $output = null;

  // Get image metadata
  $image = wp_get_attachment_metadata($attachment_id);

  // Set upload directory for image URLs
  $upload_dir = wp_upload_dir();
  $upload_url = $upload_dir['baseurl'] . '/' . dirname($image['file']) . '/';

  // Build array of sizes for srcset attribute
  $sizes = array();
  foreach ($image['sizes'] as $size) {
    $sizes[$size['width']] = $upload_url . $size['file'] . ' ' . $size['width'] . 'w';
  }
  
  // Sort sizes, largest first
  krsort($sizes);

  // Get image alt text
  $image_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);

  // Generate output <img> tag
  if (!empty($sizes)) {
    $output =  '<img srcset="' . implode(', ', $sizes) . '" ' .
               'src="' . $upload_url . $image['sizes'][$default_size]['file'] . '" ' .
               'alt="' . esc_html($image_alt) . '" />';
  }
  
  // Return/echo output
  if ($echo) {
    echo $output;
    return true;
  }
  else {
    return $output;
  }
}

Let’s just examine what’s going on here.

The function takes three input parameters. An attachment ID, a default size (for the old school src attribute), and a boolean for whether to echo the output or just return it.

First, we get the attachment metadata and put it into $image. You can see more about what the wp_get_attachment_metadata() function does here.

Next, we set up the $upload_url variable to be the full base URL to the WordPress uploads directory. That’s because the metadata output only includes the filename of each sized image, not its full URL.

Then we loop through all of the sizes in the metadata output, generating a series of strings containing the image URL and its width, for use in the srcset attribute. We put these into an array because we need to manipulate the list a bit: we need to sort it so the largest images come first, and then later we need to implode() this into a comma-separated string.

Of course we also need the image’s alt text, so we grab that with get_post_meta() which you can read more about here.

Finally, assuming we actually have some size data, we build the <img> tag, complete with srcset attribute! Then we either echo or return it, as determined by the $echo input parameter.

Something else I’d like to try with this is taking it a step further by adding a filter that processes page content, looking for <img> tags, and automatically inserts the appropriate srcset attribute.

There you have it. I welcome anyone who’s reading this to give the function a try in your WordPress site, and let me know how it goes!

Responsive Web Design: A Practical Approach (Part One… Again)

With exactly three posts here all summer, the last being nearly two months ago, it might be reasonable to assume this blog had been abandoned. Wrong! I have simply been so busy, building so many responsive websites, that I haven’t had time to gather my thoughts to share in anything longer than 140-character bursts.

“‘Responsive’ websites?” you say, and I hear the internal quotation marks in your voice. Yes. If you don’t know what responsive web design is… well, let’s be honest. You found this post, if you found it at all, when you googled “responsive web design” so I suspect you have at least a passing familiarity with the term. So let’s get started.

(Actually, before we get started, a quick note: astute observers may… um… observe that I wrote a seemingly identical post to this one back in June. And yes, that’s right. But after a summer immersed in this stuff, rather than continuing from there with “part two” it felt better to start over from the beginning with a more in-depth introduction.)

Getting Started, or, rather: How I Got Started

I’ve owned an iPhone for about 4 1/2 years now, and one of the first things I noticed shortly after it became the hottest thing around was that everyone was suddenly creating mobile websites. There were even services created just to help you convert your website into a mobile website. But it was always a separate experience (usually with a domain name that started with m.) and invariably an inferior one.

A lot of websites still do that, and it still sucks. It’s two separate websites, which is bad for users — often content doesn’t make it to the mobile site, and when that happens there’s no easy way to get to it on the desktop version — and it’s bad for site owners — double (or more) the work.

But about a year ago I started to notice a new approach, one that didn’t require two separate websites, and one that, owing partly to how quickly it caught on with the superstars of web design, usually yielded much better looking results: responsive web design (which I will henceforth lazily refer to as RWD). RWD uses CSS3 media queries to detect the window/screen size the page is displayed on, and changes the layout of the page to suit the screen. On the fly. Same page. Same CSS.

So there is no mobile site, no desktop site. There’s just the site. And it looks great on any screen.

In theory.

Of course, this solution is not perfect. But it is better in so many ways — standards compliant, future-proof, user-friendly, easy to maintain — that it is clearly the optimal solution for mobile websites today.

Getting Started (you, this time)

Before you delve into RWD, there are a couple of things you need to know: 1) HTML5 and 2) CSS3. More specifically, you need to embrace the concept of semantic HTML fully, as a well-structured HTML document is essential to the responsive approach.

I assume if you’re thinking about RWD, you’ve long since abandoned table-based layouts, and you probably don’t even remember the <font> tag existed, right? Right. But for RWD to work well you need full separation of your visual design from your document structure.

My personal preference is to take this to an extreme: I never even use <img> tags except in body content. All visual elements of the layout are contained in my CSS, even logos, and I avoid using images wherever possible. By taking full advantage of the visual effects offered by CSS3, and accepting “graceful degradation” in older browsers (or, in reverse, “progressive enhancement” in newer ones) — a topic we’ll get to in a bit — you can create a lean, well-structured site that is ripe for the responsive treatment.

Building Blocks

Nothing starts from nothing. (Whoa, that’s heavy.) And certainly a responsive website doesn’t (or generally shouldn’t) start from scratch. There are three building blocks that I now include in every site I build out:

reset.css

Created by CSS guru Eric Meyer, reset.css is a handy little file that removes all styling, which can vary between browsers, from all HTML elements, allowing you to “reset” the design and start with a clean slate. Just remember that it means you’re going to have to redefine everything — I guarantee your CSS file will eventually contain strong { font-weight: bold; } and em { font-style: italic; } but that’s the price you pay for complete control.

html5shiv.js

Developed (or at least maintained and expanded upon) by Remy Sharp, the purpose of html5shiv.js is to enable support for new HTML5 elements in older, but still widely used, non-HTML5 browsers like Internet Explorer 8 and earlier. You don’t have to use the new tags like <article> and <nav> to do RWD, but it’s fun, and feels like the future.

jQuery

There are a handful of popular JavaScript libraries out there whose goals are generally to 1) standardize inconsistent JavaScript across browsers, and 2) make working with the DOM easier, so you can do cool, standards-compliant, cross-browser compatible animations and interactivity with just a line or two of code. jQuery is arguably the most popular of these, and is my personal favorite. Again, this is not strictly required for RWD, but I use it all the time, and often in ways that enhance the capabilities of my responsive layouts. (One specific example: it’s great as a foundation for resizing complex elements like slideshows… of course, for that matter, it’s great for making the slideshows in the first place.)

Finding Your Break(ing) Point(s)

The grand vision of pure RWD is a fully fluid layout that scales dynamically to any screen size, and a grand vision it is indeed. But we are living in an imperfect world, with many factors to consider.

In my case, I typically work with outside designers. Designers who appreciate and support RWD but are not immersed in its intricacies like I am. And I don’t want them to have to be. So as a hybrid developer-designer, I make use of my somewhat unusual but not especially unique skill set to handle the responsive adaptations for them. They just deliver a “regular” web design to me, I build that out, and then I adapt and scale and shift things around as needed for the smaller screen sizes, doing my best to stay true to the spirit of the original design.

There are two keys to making this approach work:

  1. Get the designs in Illustrator format, not Photoshop. (No, seriously. You’ll find out why in a bit.)
  2. Be prepared to start thinking about break points and accept that a perfectly fluid layout is not in your immediate future.

To understand break points, you need to understand common screen dimensions. You also need to understand the importance of margins to an aesthetically pleasing layout.

For years the target screen size for web design has been 1024×768 which, delightfully, is also the effective resolution of the iPad. (Yes, the newer iPads have a high-resolution “Retina Display” which is 2048×1536, but CSS pixel measurements are “pixel-doubled” on these displays, so you don’t really need to think about high-res too much, except when it comes to images, and we’ll discuss that in a minute.)

So, we can (still) start with 1024×768. But that doesn’t mean your design should be 1024 pixels wide. You need margins, both for stuff like window “chrome” (borders, scrollbars, etc.) and also just to give your content a little breathing room. A commonly accepted standard width to use for web designs is 960 pixels, and I still stick with that.

This can sometimes cause some confusion for designers who are used to the fixed palette of a printed page. Your content can/should go all the way to the edges of that 960-pixel layout, and you still need to think about what comes outside of that area. So it’s good when you’re designing to think of foreground and background. Have an arbitrarily huge background canvas, with a 960-pixel-wide by whatever-pixel-tall box floating top-center over it, where your foreground content will go.

But I digress. We start with 960. That’s our maximum break point. (OK, if your audience is primarily looking at the site on 30-inch displays, you might want to consider an additional larger break point at 1200 or so.) Then we move down from there. I like to think of it like this:

Device/Screen Type Screen Width Content Width #wrapper CSS
Large computer displays (optional) 1280 and up 1200 margin: 0 auto;
width: 1200px;
Computer/iPad (landscape) 1024 960 margin: 0 auto;
width: 960px;
iPad (portrait) 768 720 margin: 0 auto;
width: 720px;
Small tablets/phones Varies Fluid margin: 0 auto;
width: 90%;

The “small tablets/phones” layouts typically collapse to a single column and are the only truly fluid layouts I use; the larger break points go to fixed widths, which makes for easier scaling of columnar content.

Note that I typically follow the convention of placing everything inside my <body> tags inside a <div id="wrapper"> tag, which allows me to apply CSS to the overall page body and separate CSS to the foreground content (what’s inside the “wrapper”).

Occasionally I will split “small tablets/phones” into two separate break points, with small tablets somewhere between 500 and 640 pixels. I may also change the content widths somewhat to suit the specifics of the design.

Mobile-First Sounds Great, but Let’s Be Honest: It’s Really IE8-First

Earlier in the year, Luke Wroblewski took the idea of RWD a step further with his inspired vision for Mobile-First web design. Initially I wholeheartedly embraced mobile-first, but I’ve since reconsidered.

What is mobile-first? It’s RWD, but instead of starting from the desktop layout and using CSS3 media queries to adjust the layout to smaller screens, it starts from the small screens and works its way up. The main benefit of this approach is that it allows you to prevent mobile devices from loading unnecessary assets (images, etc.) that they won’t actually use.

There’s a major downside to mobile-first, however, at least in my experience trying to implement it: there are still a lot of people using Internet Explorer 8 (and earlier), which does not support CSS3 media queries. So unless you create an IE-specific stylesheet (using conditional comments), IE8 and earlier users will be stuck with a strange variation on the phone version of your site.

So after building a few mobile-first RWD sites, I have abandoned that approach, and gone with what could be called an IE8-first approach. I am not really building to IE8. I work primarily on a Mac, and I preview my work in Chrome while I’m developing. But what I mean is I’ve gone back to that standard 1024×768 screen as the baseline for my CSS, with CSS3 media queries for the smaller screen sizes (as well as for print and high-resolution displays, the latter of which is next up).

Getting Retinal

Remember earlier when I said your designs should be in Illustrator rather than Photoshop? Here’s why: high resolution. Sure, you can change resolution in Photoshop too, but… wait, you’re not still slicing-and-dicing, are you? By working with discrete objects in Illustrator, resolution-independent and, when possible, vector-based, you have the maximum flexibility when you render these objects out as 24-bit PNGs with alpha channel transparency. (You are doing that too, right?)

Starting with the iPhone 4, Apple introduced the “Retina Display” which is their marketing term for, basically, screens with pixels too small for you to see. The goal is to achieve a level of resolution on an LCD screen that rivals print. The exact pixels-per-inch varies from screen to screen, and is not really too significant. The key point is that above a certain pixel density threshold, CSS treats all pixel-based measurements as pixel-doubled. As I noted above, although the current iPad screen resolution is 2048×1536, its effective pixel size in CSS is still 1024×768. There is a practical reason for this (if CSS stuck with the actual pixels, all web pages would appear absurdly tiny on such a screen). But there’s also a practical downside: most images on most web pages are now being scaled up in the browser to these pixel-doubled dimensions, resulting in a blurry appearance.

But here’s something really cool: you can specify the display dimensions of an image in CSS, and the browser will scale the image down on-the-fly. This has been the bane of many web developers’ existence for years, where people who didn’t know better would upload a very large, high resolution photo and scale it down in the page, resulting in ridiculous download times as the image slowly drew in on the page.

Used effectively, however, this characteristic provides an extremely easy way to make images high-resolution on displays that support it. By using CSS to scale the dimensions of an image to 1/2 its actual pixel size, the image will display in full resolution on screens that support this.

Of course, doubled dimensions mean quadrupled pixels, and depending on the details of JPEG or PNG compression, the high-resolution images may be more than four times the file size of their standard-resolution equivalents. So it’s nice to, again, use CSS3 media queries to only deliver these high-resolution replacement images to screens that can display them properly. (This will be demonstrated in the full example code below.)

You Say Graceful Degradation, I Say Progressive Enhancement

The matter of graceful degradation and/or progressive enhancement (depending on how you look at it) is tangential to RWD, but it’s something you’re likely to be dealing with as you build a responsive website.

Not all browsers support all CSS3 capabilities, but that doesn’t mean you shouldn’t use them. I’m especially fond of box-shadow and border-radius, and in working with RWD you’ll probably get quite familiar with background-size as well. Remember that most of these newer capabilities will probably need to include vendor prefixes (like -moz- and -webkit-) as well. It’s cumbersome, and will probably be as painful to clean up as <blink> tags in a few years, but for now it’s the way to get things done.

The biggest challenge with progressive enhancement may well be convincing site stakeholders that it’s OK for the site to look (subtly) different in different browsers. Then again, if you’re doing RWD, that should be a given.

So, What Does This Actually Look Like?

As I’ve iterated my RWD approach this summer, I’ve inched closer and closer to a standard template I can use to start a new website. I feel it’s not quite there yet, but my basic CSS file structure is standardized enough that I can share it here. In a subsequent post, I hope to provide a zip download containing a full template file set for creating a new responsive website.

Here’s a rough example of what my typical CSS file looks like. Again, personal preferences dominate here: I like to write my CSS from scratch, and I typically organize it into three sections: standard HTML (basic tags), CSS classes (anything starting with a period), and DOM elements (anything starting with a hash mark).

The idea is that we’re going from general to specific. Within the standard HTML and CSS classes I alphabetize everything, so it’s easier to find things to change them as I go. Within the DOM elements I try to keep everything in the order it actually appears in the HTML structure. (I also alphabetize the properties within each element definition… but that’s just because I’m anal retentive.)

Sample CSS File

/* IMPORT */

@import url('reset.css');

/* STANDARD HTML */

body {
  font-size: 100%;
  line-height: 1.5em;
}

/* CSS CLASSES */

.column {
  float: left;
  margin: 0 5% 1.5em 0;
  width: 45%;
}

/* DOM ELEMENTS */

#wrapper {
  margin: 0 auto;
  width: 960px;
}

#logo {
  background: transparent url('img/logo.png') center center no-repeat;
  -moz-background-size: 250px 100px;
  -webkit-background-size: 250px 100px;
  background-size: 250px 100px;
  height: 100px;
  width: 250px;
}

/* CSS3 MEDIA QUERIES */

/* PRINT */
@media print {

  * {
    background: transparent !important;
    color: black !important;
    text-shadow: none !important;
    filter: none !important;
    -ms-filter: none !important;
  }
  @page { margin: 0.5cm; }
  h1, h2, h3, p { orphans: 3; widows: 3; }
  h1, h2, h3 { page-break-after: avoid; }
  pre, blockquote { border: 1px solid #999; page-break-inside: avoid; }
  abbr[title]:after { content: " (" attr(title) ")"; }
  a, a:visited { color: #444 !important; text-decoration: underline; }
  a[href]:after { content: " (" attr(href) ")"; }
  a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; }
  img { max-width: 100% !important; page-break-inside: avoid; }
  thead { display: table-header-group; }
  tr { page-break-inside: avoid; }

}

/* LARGE TABLETS (UNDER 1024 PIXELS) */
@media screen and (max-width: 1023px) {

  #wrapper {
    width: 720px;
  }

}

/* SMALL TABLETS/PHONES (UNDER 768 PIXELS) */
@media screen and (max-width: 757px) {

  #wrapper {
    width: 90%;
  }

}

/* HIGH-RESOLUTION DISPLAYS */
@media only screen and (-moz-min-device-pixel-ratio: 1.5),
    only screen and (-o-min-device-pixel-ratio: 3/2),
    only screen and (-webkit-min-device-pixel-ratio: 1.5),
    only screen and (min-devicepixel-ratio: 1.5),
    only screen and (min-resolution: 1.5dppx)
{

  #logo {
    background-image: url('img/logo_x2.png');
  }

}

The Test Suite

Of course, all of this work means nothing until we’ve seen what it actually looks like in the web browsers on these different devices. To that end, a decent test suite is essential.

One cool trick about RWD, which is not only useful to dazzle clients when pitching a RWD approach to their websites, but is also helpful for quick testing as you go, is that the responsive approach works simply by making your browser window smaller on a computer. So you can shrink the window down and approximate what the site will look like on a tablet or a phone without actually having one in your hand at all times.

But before you go live, you do need to test it for real on different devices, just like you need to test in different browsers. The table below shows my test suite. It’s not comprehensive, but it’s practical, and it all fits in one small messenger bag.

Device Operating System Browser(s)
MacBook Air Mac OS X Mountain Lion Chrome (latest)
Firefox (latest)
Safari (latest)
MacBook Air
with Boot Camp
Windows 7 Internet Explorer 9
Chrome (latest)
Firefox (latest)
MacBook Air
with Parallels Desktop
Windows XP
(3 separate virtual machines)
Internet Explorer 8
Internet Explorer 7
Internet Explorer 6
Firefox 3.6
Note: I only offer my clients very limited support for IE6.
iPad (Retina Display) iOS 6 Mobile Safari (latest)
Chrome (latest)
iPhone (Retina Display) iOS 6 Mobile Safari (latest)
Chrome (latest)
Samsung Galaxy Player 4
(high-resolution)
Android 2.3 Android web browser

Give Me Something I Can Print!

You may have noticed in the full example CSS above that I included CSS3 media queries for print. The need for decent print output will vary by project — different sites’ audiences may be more or less inclined to print out pages. In general I think of printing out web pages a bit like I think about… well, honestly, I can’t even think of a good analogy. You just shouldn’t do it. But sometimes it has to happen. I won’t be exploring the infuriating nuances of print CSS here, other than to say that if you do need to support printing, the code provided in this sample is a good place to start. (Sadly, although I use it regularly, I neglected to make note of its source. If you know where it’s from, please let me know in the comments.)

Where Do We Go Now?

OK Axl, hang on. I know I’ve dumped a lot on you here to think about, without necessarily providing enough specifics. But that’s kind of the point: in order to do this right, you really need to learn it for yourself and gain the experience of building RWD sites directly. This is what has been working for me but my approach is certainly neither the only nor the best way, I’m sure.

My hope is to follow up this post with a “Part Two” entry this time around, where I get into more of the specifics of an actual example website. In the meantime, experiment and discover! And be sure to check out the entire A Book Apart series, as they provide the conceptual and detailed knowledge needed to get started with this exciting new approach to web design.

Practical responsive web design, part one

I’ve been wanting to write this post for a while, but I’ve been too busy writing code instead. Plus, the techniques are evolving and changing so fast, that by the time I finish a project, the way I built it is already obsolete.

Now, with the Breaking Development Conference in town and a few recent responsive site launches under my belt, it seemed like a good time to write up a summary of what I’ve learned, what I’m doing, and where I think all of this is going.

First, a quick aside. I didn’t attend the conference. I would have liked to, but as an independent developer I never seem able to justify the standard $500-per-day rate most conferences charge. That doesn’t mean the conferences don’t have value; they’re just not for me.

Before we begin

There are a few caveats I want to lay down before I start talking about responsive web design:

This stuff is changing… fast. Anything I write here may become foolishly out of date by the time I hit the “Publish” button. Responsive web design is a work in progress, and there are no rules (yet).

What I’m doing may not be “by the book,” proper-name Responsive Web Design. The book is great, and there are “experts” who have much deeper knowledge of these strategies than I do. But as I said above, there are no rules (yet). I want to describe the practical techniques I am employing on actual live web projects, under often less-than-ideal circumstances.

Every website is different. The company is different. Its audience is different. The content and style and context where it will be viewed are different. The balance between showing off fancy new features on high-resolution tablet displays and supporting corporate IT departments that are still straggling with Windows XP and Internet Explorer 6 will vary. In short, what I am doing may not work for you. But I hope it can give you some ideas that will.

A practical baseline

My goal with responsive design is to get the biggest “bang for my (client’s) buck.” I recently read a about a study that found almost 4,000 different Android devices in a site’s access logs, with many of them only appearing in the logs once. It is not possible to account for all of these variations. And, after its primary goal of providing an optimal user experience across a variety of devices, not needing to account for each of them individually is the second biggest purpose of responsive design. (That’s also, arguably, its biggest practical benefit.) By building on a fluid, flexible structure from the beginning, a site will look good regardless of slight variations in its presentation.

But I’m not starting from scratch. I work with a number of designers who deliver their work to me in a variety of formats (usually Adobe software). They’re tremendously talented, but they don’t all have a full working knowledge of fluid grids and all of the other considerations that go into responsive web design. So my job is largely to translate these “traditional” web designs into something that works, more or less, with a responsive approach.

I’m targeting three basic screen types: computer (desktop or laptop, including iPad in horizontal orientation), tablet (primarily iPad in vertical orientation, but also smaller tablets like the Kindle Fire or the Nook Color), and smartphone (primarily iPhone, but also Android and Windows Phone). Additionally, I am trying to balance a Mobile First approach with support for Internet Explorer 7 and 8. (I am fortunate to be in a position not to need to worry much about IE6 anymore, and IE9 plays well with CSS3 media queries.) In some cases I am also targeting “very large” computer displays, those with a horizontal resolution of 1280 or above, with a scaled-up layout.

So, instead of accounting for 4,000+ different screens, I’m aiming at 3 (or 4) general screen categories. I am also accounting for two basic browser categories: IE 7 and 8, and everything else. (Yes, if you approach it in the right way, it’s really that simple. Almost.)

Fixed, yet flexible

With this “practical baseline” in mind, and working primarily with traditional fixed-width web designs as a starting point, I’ve established break points (widths at which the layout changes significantly) at around 700 pixels (varying by site between 640 and 720); at 960 pixels for the “standard” computer (and horizontal iPad) layouts; and, for the “very large” displays, at 1200 pixels. This allows for a traditional fixed-width web design approach to be used, rather than accounting for a completely fluid layout across all screen sizes. It may sound like a cop-out, but I find it to be a very helpful way to get things done when collaborating with designers who are not living and breathing this stuff the way I do every day.

For screens below my “around 700” threshold, I drop into a fully-fluid, single-column layout targeted at the smartphone user experience. In these cases there may be other significant changes to the layout, such as collapsing content blocks into expandable buttons, allowing users to quickly see what’s on the page without having to scroll endlessly. (This is not a radical invention of my own… it’s more-or-less how the mobile version of Wikipedia functions.)


In part two, I will get into the details of how I built out a pair of recent websites, including a few code examples, to show how the HTML and CSS fit together, and how I balance the seemingly incompatible worlds of mobile-first and IE8.