Cloud Four Blog

Technical notes, War stories and anecdotes

Two pretty-good techniques for styling tricky form elements

Confession time: For most of my career, I despised form elements. Checkboxes, radios, selects and file inputs seemed to gleefully defy what little control I expected from an HTML element. Their penchant for idiosyncracy drove me to almost as much hair-pulling and teeth-gnashing as IE6 or web-safe fonts.

These days, my frustration with form elements has quieted. Partly that’s because browsers and development tools are so much better. But more significantly, I now understand the benefits of surrendering some control to the operating system. As devices continue to accept a greater and greater variety of input methods (keyboard, mouse, touch, voice, gesture, remote, etc.) while browsers adopt an astounding variety of new input types , it’s a gift for vendors to provide default experiences consistent with the user’s expectations of the platform.

So I no longer strive for “pixel perfection” when styling form elements. I don’t need absolute control. All I want is something easy to tap that feels intentional.

When the browser defaults don’t get me there, here are my go-to workarounds.

Checkboxes and Radios: Styled Sibling

This technique works in any browser that supports CSS3 selectors (basically IE9+). If you read Radio-Controlled Web Design a few weeks ago, this should feel familiar. Let’s start with a checkbox example.

We’ll need a few HTML elements:

  • The <input> itself.
  • A dummy element to style (right next to the <input>).
  • A containing <label> that passes click events to the aforementioned <input>.

I like to wrap the <input> and dummy elements in a container to keep everything nice and tidy, but strictly speaking it isn’t required. Here’s what that markup might look like:

<label>
  <span class="checkbox">
    <input type="checkbox">
    <span class="checkbox-value" aria-hidden="true"></span>
  </span>
  Set phasers to stun
</label>

We’re now free to visually hide the checkbox, styling .checkbox-value however we like:

/* hide the "real" checkbox visually */
.checkbox input {
  border: 0;
  clip: rect(0 0 0 0);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  width: 1px;
}
 
/* style the "fake" checkbox */
.checkbox-value {
  /* default/unchecked styles */
}
input:checked + .checkbox-value {
  /* checked styles */
}

When the user clicks the label, the click is passed along to the <input>, which toggles the state of :checked, which affects the appearance of .checkbox-value.

Here’s an example that styles the checkbox like an iOS-style switch:

See the Pen Styled checkbox by Tyler Sticka (@tylersticka) on CodePen.

Here’s the same idea applied to radio buttons with a slightly more conventional design (incorporating a base64-encoded SVG checkmark):

See the Pen Styled radios by Tyler Sticka (@tylersticka) on CodePen.

This technique has a few drawbacks. It requires some extra markup. It won’t work in IE8 or earlier without a fallback. It could probably use another pass for accessibility. But compared to most of the JavaScript solutions I’ve tried, this feels straightforward, consistent and predictable.

Selects and File Inputs: Transparent Overlay + JavaScript

For more complex elements like <select> and <input type="file">, we can’t get by on CSS alone (though it gets us further than one might expect).

Our markup is similar to the previous set of checkbox/radio examples, except we won’t need a <label> for click events:

<div class="select">
  <select>
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
  </select>
  <span class="select-value" aria-hidden="true"></span>
</div>

Instead of hiding the <select> entirely, we want to position it over the rest of our element, allowing it to intercept click events and correctly position any dropdown it may display. Because this technique relies on JavaScript, we’ll qualify some of our selectors with .js (since you’re probably already using Modernizr).

.js .select {
  position: relative;
  /* default styles */
}
.js .select:hover {
  /* hover styles */
}
.js .select.focus {
  /* focus styles */
}
 
/* nicer default styles for "real" <select> */
.select select {
  cursor: pointer;
  display: block;
  width: 100%;
}
/* hide and overlay when JavaScript is enabled */
.js .select select {
  left: 0;
  height: 100%;
  min-height: 100%;
  min-width: 100%;
  opacity: 0;
  position: absolute;
  top: 0;
}

Already, this “works.” Options will display on click. But there are some problems. The value doesn’t update. There are no hover or focus styles. That’s where JavaScript comes in!

(Although I’ve chosen to write this in jQuery for the sake of readability, remember: You Might Not Need jQuery!)

// For each .select element
$('.select').each(function(){
  // Save some elements as variables
  var $element = $(this);
  var $select = $element.find('select');
  var $value = $element.find('.select-value');
  // Bind event handlers to <select>
  $select.on({
    // On change or keyup, update the value text
    'change keyup': function () {
      $value.text($select.val());
    },
    // On focus, add the focus class
    'focus': function () {
      $element.addClass('focus');
    },
    // On blur, remove the focus class
    'blur': function () {
      $element.removeClass('focus');
    }
  });
  // Trigger the change event so the value
  // is current
  $select.trigger('change');
});

Here’s how all of that comes together:

See the Pen Styled select by Tyler Sticka (@tylersticka) on CodePen.

With some tweaks, the same basic technique can also work for file inputs (assuming experimental WebKit/Blink features aren’t your thing):

See the Pen Styled file input by Tyler Sticka (@tylersticka) on CodePen.

This idea isn’t new. Peter-Paul Koch wrote about it quite a while back. Yet I rarely see it in use outside of a few large mobile frameworks. I’m honestly not sure why.

…and beyond?

What do all of these examples have in common? They don’t mess with the form element too much! By worrying less about customizing behavior and more on simply triggering it, we can indulge some of our designerly impulses without discarding all a given platform has to offer.

Consistency and functionality… no hair-pulling or teeth-gnashing required!

Update: September 8, 2014

A reader pointed out that the select example wasn’t responding to keyboard input in Firefox. I discovered that Firefox doesn’t fire the change event for selects like other browsers do, so I’ve updated the demo and example code so that it binds to both change and keyup.

I also learned that Firefox doesn’t show the full dropdown on any keypress, but this seems to be true of unstyled <select> elements as well. I encourage developers to use these examples as a starting point, and to augment usability shortcomings on a case-by-case basis if the default browser behavior isn’t cutting it.

Fixed and inflexible

Even before smartphones came along and dashed any hope for a 960-pixel-wide web, designers and organizations have struggled with the challenge of prioritizing and composing content that scrolls. Our screens act like windows to content of variable size and scale, demanding an awful lot of abstract thinking to design for. Sometimes we’re successful, revising content, designing modern day deliverables and embracing compromise like we know in our hearts we should. Other times, we convince ourselves that we can predict this inherently unpredictable medium, making decisions that age quickly and poorly by prioritizing the window instead of the content.

Most recently, I’ve noticed a sharp uptick in the number of requests I receive to explore fixed-position (aka “sticky”) interface elements. Fixed elements are positioned relative to the viewport instead of the page, allowing them to maintain position even as the document scrolls. Some of the most popular sites on the web employ “sticky” menus, and with good reason… when applied thoughtfully, they can yield substantial usability improvements.

But when fixed positioning is used without care, restraint or precision, it can have disastrous consequences. Here are some of the reasons why.

We can’t predict how much space we have.

Our industry has a nasty habit of quietly embracing display resolution “standards” that are mostly fantasy… design decisions are a lot easier if you assume all devices are 320 pixels wide by 480 pixels tall (and users never turn them sideways). The inconvenient truth is that display resolutions vary wildly. Each additional “sticky” element increases the risk of obscuring the page content mostly (or entirely) for some users… in which case the page might as well not exist at all.

We can’t get those pixels back.

Fixed elements aren’t just “prominent,” they photobomb the interface, robbing focus and attention from what really matters — the content! Before you make something “sticky,” consider reevaluating the element’s importance relative to the entire page (instead of on its own merits).

It makes scrolling tougher.

As evidenced by the years-long debate over “The Fold,” the fear that users won’t know (or lack willingness) to scroll persists to this day. When that fear is real, then fixed positioning is a godsend, ensuring the visibility of content regardless of scroll position.

But those fears don’t mesh with reality very well.

Today’s users are so familiar with scrolling that most mobile browsers will hide the scrollbar entirely. “Sticky” elements complicate matters by reducing or obscuring the scrollable area, forcing the user to swipe more carefully to avoid accidental actions.

Ironically, our desire to alleviate the supposed “difficulty” of scrolling may make scrolling that much more difficult!

It can slow everything down.

Users care about speed. But speed isn’t all about navigation… there’s also the overall speed of the experience. Fixed positioning can result in strange browser-specific quirks or even costly repaints, potentially counteracting any efficiency you might have gained.

It may not actually work.

Mobile websites share a lot of their design vocabulary with native mobile apps, where fixed headers, menus and tab bars are commonplace. This makes it easy to forget that fixed positioning as we know it is relatively new to the web, and often unreliable.

“Sticky” headers, footers and navigation flourished in the 1990s, often implemented using frames. When frames fell out of fashion in the early 2000s, most browsers did not support fixed positioning using CSS. In the absence of frames, position: fixed or consistent, intuitive JavaScript, fixed positioning became just another discarded Web 1.0 trend… at least until CSS support arrived in IE7.

But smartphone browsers have historically not supported position: fixed as predictably as their desktop counterparts. It was entirely absent from mobile Safari prior to iOS5, and largely unusable in Android browsers prior to Honeycomb. To this day, behavior can be inconsistent across platforms. To quote Brad Frost in his excellent post on Fixed Positioning in Mobile Browsers, “‘support’ isn’t exactly binary.”

Since you can’t rely on support for fixed positioning, you’ll need to make sure your experience works without it anyway. Which begs the question…

Why position: fixed at all?

I believe there are plenty of interface elements that benefit from fixed positioning, provided they follow a few best practices:

  • The “sticky” element is clearly more important than everything else on the page.
  • The footprint of the element is modest enough that it does not obscure too much of the page content (even in landscape).
  • Any efficiency gained from the element’s consistent availability is significantly greater than any lost as a result of the element’s inclusion (due to performance, obscuring of page content, etc.).
  • There should only be one “global” (navigation, tab bar, etc.) and one “temporary” (modal, dialog, etc.) fixed-position element on-screen at any one time.
  • Fixed positioning should always be an enhancement. Your interfaces should never rely on it.

If any of these considerations completely upend your design aspirations, you may want to rethink your user experience with less rigidity. As John Allsopp so aptly put it fourteen years ago, “The journey begins by letting go of control, and becoming flexible.”

Did you try to reach us?

I’m embarrassed to admit it. I screwed up and if you tried to contact us over the last few months, there is a chance your message didn’t get through.

Specifically, messages sent via the contact form on our site weren’t always reaching us.

In case this saves anyone else from making the same mistake, here’s what happened. We switched our mail to Google. Instead of having an email alias, we had to use a Google Group.

Everything seemed fine for a few months, but then at some point Google Groups decided contact form submissions were spam. And we didn’t have any moderators for the group.

I set up the Google Group so I must have screwed it up. Because things worked great for several months, we don’t know when the problem started and how many messages were missed.

The most painful part about screwing up something like this is that there is no way to know who you need to apologize to.

So if you tried to contact us and didn’t hear back, I’m very sorry. The contact form is fixed now. We’d love to hear from you.

Beyond “Hello, World” with Gulp

(This post is for: web developers who have used, or thought about using, a build tool before, are JS-comfy and maybe have noodled around in node.js but wouldn’t, say, feel up to submitting a talk to a node conference.)

It would be hackneyed to call the last twelve months the “Year of Build and Workflow” for web developers, but there’s an element of reality to the contrivance. In 2013, there was grunt (heck, there still is; it didn’t die or anything) and a whole lot of blog posts about streamlining workflow around SASS and templating and build package management, etc.: topics that were—poof!—suddenly an imperative for general people working on the web. I wrote a thing about workflow for A List Apart earlier this year, a few weary weeks after the whole “Oh, you learned grunt? Sucker! Now you need to learn gulp, because whatever!” revolution happened.

Summarized as this: a whole lot of people (increasingly non-nerdcore) learned to use grunt to wrangle previously-tedious workflow tasks for building web sites. This represented a big jump in things we all needed to know. And then, kind of literally overnight, there was gulp. For me, this felt like a burden as well as an opportunity.

I wasn’t exactly a holdout (as you can see), but I was initially resistant to throw the grunt baby out with the 2013 bathwater simply because a new tool existed. And, like maybe some of you (?), I found the initial sell a bit baffling: “streaming build system?” I didn’t know I wanted that? Awesome syntax? I didn’t really have a gripe with grunt on that front. “Speed?” Maybe? I didn’t exactly have to go brew a cup of coffee while my grunt tasks ran.

Grieving and Surmounting

But smart people I know kept extolling its highlights and I decided to give it a whirl. The familiar stages of dev-new-tool excitement-grief happened:

  1. Find and install new tool that people crow about.
  2. Get satisfying example configuration/program running using new tool.
  3. Extend satisfying example configuration/program in a tiny way and find success in making it do something useless, but cool. HELLS YEAH.
  4. Extend awesome slightly-extended configuration/program in another way to make it do something you actually need it to do. Spend 3 hours/days progressively assuring yourself you are a moron—this should really be so easy! Two possible outcomes: rage quit or eventual, sweat-soaked breakthrough.
  5. Assuming you’ve made it this far, progress with a slight wariness, possibly even progressively assuring yourself that the tool devs or Stack Overflow or Google or a particular plugin or, hell, the entire language you’re working in is the real moron here. Also revel in the fact that extant examples of what you’ve now managed to do exist on the Internet at all—you’ve birthed something truly novel. This is often a necessary step to repair the psyche.
  6. If you are kind, you then help other people avoid step 4 (or, at least, put a reassuring hand on their shoulder).

Gulp: The Good

Here’s some of why you might want to use gulp instead of another alternative:

  • Pretty syntax and intuitive structure: There is nothing wrong with grunt’s syntax, but gulp’s is kinda pretty. Using Streams means you’ll be able to do a lot of chaining, which always feels pleasing to the code-scanning eye. I was never a huge fan of the double-step grunt convention of grunt.loadNpmTasks() and grunt.registerTask(). In gulp you can require() and define gulp.task()—that feels more natural to me. I find I don’t have to look up core API stuff for gulp; with grunt, I never memorized it.
  • Speed: There’s no doubt. gulp feels noticeably fast. That is not exactly a scientific observation, but I stand by it.
  • Streams: If you know node already, gulp’s Streams architecture will make you feel right at home.
  • Gulp has a nice clarity that it is about working with streams of files. As such, there is more symmetry between any two given gulp tasks than most given grunt tasks. gulp.src globs and gulp.dest paths become second nature. Stream in, though, out.
  • Works with lots of things, easily: Like grunt, gulp has plugins (many of them). But the first edict in the guidelines for creating a gulp plugin is: “Your plugin should not do something that can be done easily with an existing node module,” meaning that gulp encourages the use of non-plugin-i-fied node packages wherever possible (versus “[w]rapping every possible thing just for the sake of wrapping it”). The plugin landscape feels correspondingly more serene.

Avoiding Step 4: Tips for Getting along with Gulp

  • Make sure your gulp tasks finish correctly. If not, it will wreak havoc with dependencies and other tasks. Be sure to read the section of the docs about valid things to return from gulp tasks and how to handle async tasks. Trust me on this one.
  • In fact, read the entire API documentation. If this sounds like a tall order, take note that it is shorter than this blog post. The core API for gulp is outstanding in its simplicity.
  • Get an understanding of Streams, a core node construct, because this is the way that gulp works. Take a few minutes/a while and read a primer on Streams. It’s a bit to get your head around, but if you’re doing any heavy lifting with gulp (or other node, for that matter), you’ll be glad you learned.
  • Watch out for plugin quality. The plugin landscape may be straightforward, but it’s young, and there are some stinkers. I lost some serious time to a couple.
  • Dig hard for real-world (read: complex) examples. This situation has gotten better in the past few months. Dan Tello’s excellent post on Gulp + Browserify: The Everything Post is a must-read-right-now. When I first encountered his repo full of organized gulp tasks, it changed my everything. I ended up extending my fork to handle dependencies effectively, but his gulp-starter repo has since been updated to do that, also, so, win! There is more documentation and examples out there now than there was a few months ago. But documentation about gulp things can sometimes presuppose that you know more about various concepts than—gasp—perhaps you do. Don’t fret. That jargon sounds weird to other people, too. Read slowly and give yourself some time!
  • Watch out for plugins getting between you and what you’re doing. Like any build tool with plugins, gulp puts a layer between you and (in gulp and grunt’s case) node. Sometimes it’s hard to debug whether you’re doing it wrong, or whether the plugin between you and the wrapped node package is doing something wrong (or at least making things real complicated). If you don’t understand the syntax of a plugin or what it’s doing, consider that a red flag and slow down until you do. Or: see if you can accomplish what you’re doing with a node module instead.
  • Complexity explodes as you add more tools to the mix. We are using browserify for our application code, but it got outrageously onerous for managing vendor code, much of which was not modular in any sensical way (this was serious step-four territory). We ended up throttling down and using something a bit simpler. Don’t be afraid to over-simplify if it gets the job done. I find you can usually kick up complexity later, when needed, but that the opposite—dialing it down—is not so easy.

We do some really cool things at present with gulp. We use it to parse YAML front-matter out of templates (which get piped through underscore and have partials inserted and come out as static HTML files) to create an auto-index of project assets, adding automated screenshots (thanks, phantom.js!) at different widths to show responsive layout. This of course along with SASS and auto-prefixer and browserify and concatenation and and and…whew. Because each task in the works is totally modular, this ends up not feeling rickety and spaghetti, believe it or not—and that alone is worth the price of admission.

Go out and build! Let me know how it goes!

My thanks to Cloud Fourian Erik Jung for leading us out of step 4 hell vis-a-vis the whole vendor JS thing I mentioned above.


Slow and ugly

Many years ago at a previous job, I was responsible for pushing our organization to adopt a new ticket tracking system. We decided to use an open source project called Request Tracker (RT).

This was before the days of Zen Desk and similar services. RT matched our requirements best. I worked with our sysadmins and engineers to get the software running and rolled it out to the organization.

It was a failure. People were openly swearing at RT, and I’m sure they were privately cursing me for forcing them to use it.

While I sympathized with the complaints, I felt hamstrung because RT was deployed on an underpowered server and we had not been allowed to modify the look and feel. Back then RT was a bit of a dog both from a performance and aesthetics perspective.

As I worked with engineering to secure better hardware and get someone to assist with the design, the number of grievances continued to pile up.

One conversation stands out to me. A member of the management team told me that the fact that customers couldn’t reset their password in RT was unacceptable and as long as that was true, we couldn’t use RT.

I listened to the objections and kept a list of the issues that were raised, but I kept my focus on making RT faster and more attractive.

A few months later we relaunched RT. It was met with skepticism, but to the credit of my colleagues, they gave me and it a second chance.

It wasn’t too long after the relaunch that previous skeptics were swearing by the system. One of the team members became the master of RT and made a bunch of process improvements that I would have never considered.

What happened to that list of complaints that I gathered? We didn’t address a single one of them. Passwords worked exactly as they did before.

We simply made RT fast and attractive.

I have a simple rule when it comes to user experience: when something is slow and ugly, nothing else matters.

Until you address those two issues, you’re not going to be tell whether other complaints are real or red herrings.