CSS Gradients are about to Graduate!

Finally all browser vendors are on the same page when it comes to gradients

The Webkit team introduced CSS gradients on April 14th, 2008. Shortly afterwards they presented it to the W3C for consideration as a recommendation. Sometime later, Mozilla decided to implement CSS gradients using the same notation the Webkit gradients, but with the -moz prefix. After some time, however, they decided to replace that notation with a simpler one. Ever since, to do CSS gradients on the Web you had to write gradients the Webkit way for Safari and Chrome, and the Mozilla way for Firefox. Well, now all browser vendors have agreed to implement the same spec. At this time you can write a single notation that is identical for Safari, Chrome, Firefox, Opera and IE10.

Since version 5.1, Safari has supported the newer notation. Opera beta running Presto 2.10.299 fully supports the linear and radial notation, although the developer site only mentions support for the linear notation. Firefox, of course, already supports this notation. And the latest beta of IE10 does as well. This means that at some point all browsers will support this notation. Well, sort of.

Recently somebody at the W3C has been thinking a little too much. As of January 2012 the document CSS Image Values and Replaced Content Module Level 3 now has a slightly different notation. Since this just showed up, there is no support for it in any browser. And, since it is a working draft, it could change at any time. So, at this time, I’m going to ignore what the document says and just cover what the latest browsers have agreed to support.

Because CSS gradients are still a draft proposal, all browser vendors use their respective prefixes with the notation. This is a good thing since the spec is in flux. They shouldn’t change their present implementation until the spec reaches recommendation status, in which case they can implement the final version of CSS gradients without their vendor prefixes.

  • Webkit: -webkit-
  • Mozilla: -moz-
  • Opera: -o-
  • Microsoft: -ms-

CSS gradients are rendered as a background image. That means that all of the properties of the CSS background module apply to CSS gradients. In other words, you can have multiple gradients on the same element and control their size and position as well, or use them as image masks. Also, whereas in the past you might have used a background color in conjunction with a background image, you can now use a background gradients as the backdrop for a background image, or you could have a transparent gradient layered over a background image. The ability to stack up gradients while controlling their size, position and repetition means you can create complex repeating patterns that would normally require a background image. The ability to define multiple background images results in a layered affect not unlike Adobe Photoshop’s layers. The new CSS filters module will increase the comparison with Photoshop further my providing many color filters, such as reverse, multiply, dodge, burn, darken, lighten, grayscale, etc. With JavaScript you could also manipulate the properties of your CSS gradients to produce a background pattern that morphs in real time.

Linear Gradients

The notation for linear gradients is quite simple and straightforward. First thing, you’ll be defining it as a background image on an element. CSS uses functions that create the gradient according to the arguments you provide. For linear gradients, the values you’ll need are as follows:

[<point (one value, two values or degrees)>]?, <color [stop]?>, <color [stop]?>

From the above definition we can see that all values are optional, except the start and end colors.

The first value (point) is optional. If no value is provided, it will default to drawing the gradient from top to bottom. You can use keywords for the position. These can be a single keyword or a combination of two. You can also use any valid degree values. The purpose of these point definitions is to define which direction the gradient flow towards. You also need to provide at least two colors. The first color will be where the gradient starts from, and the last color will be where the point indicates. So a gradient with yellow and blue and a point value of top will start at the bottom with yellow and end at the top with blue. Here re possible point values:

– top
– right
– bottom
– left
– top left
– top right
– bottom left
– bottom right
– 0deg
– 11deg
– 67deg
– 182deg
– -45deg
– -90deg

Colors can have optional stop values. If no stops are provided, the colors will blend equally from the first to the last.You can provide as many colors as you want to create the gradient, and you can vary their widths by providing stops. The value of the stops can use any valid CSS length identifier (px, pt, em, %, etc.). The position value is placed after the color. You can use any valid CSS colors, such as keywords (red, yellow, blue), or hex, hsl, rgb or rgba values. Regardless of what the stop position is for the last color, that color will continue filling the element the rest of the way.

background-image: linear-gradient(top, yellow 10px, red 80px);
background-image: linear-gradient(top right, orange, green 30%, yellow 70%);
background-image: linear-gradient(60deg, red, white, blue 50%);

Repeating Linear Gradients

Repeat linear gradients are easy to do. Actually, the same effect can be achieved with background size and background repeat properties, but it is nice to have it I suppose. It works the same way as regular linear gradients, except that you use repeating-linear-gradient as the function:

background-image: repeating-linear-gradient(top, yellow 10px, red 80px);
background-image: repeating-linear-gradient(top right, orange, green 30%, yellow 70%);
background-image: repeating-linear-gradient(60deg, red, white, blue 50%);

Radial Gradients

The notation for radial gradients is similar to linear gradients, except that you can specific a shape argument to control how the radial is produced. Here’s the possible values:

[<position (two separate values)>]?[[<shape (literal value or length value)>] || [<size length value>]>]? <color [stop]?> <color [stop]?> 

From the above definition we can see that all values are optional, except the start and end colors, just like linear gradients.

If no value for position is supplied, the radial gradient will be centered in the element. Position is based on the center of the radial gradient. It accepts the same values as background position. Those values include percentages, lengths and keywords. Just like background positioning, you can use negative values to move the center of the radial gradient off the screen. Percentages and lengths require two values, the first defining the x axis and the second defining the y axis.

percentage: 0% 0%, 20% 60%, 50% 50%
length: 0px 0px, 24px 45px, 3em 5em

The keywords are: top, right, bottom, left and center. You could combine these in various ways:

top left, bottom right, center center, center right, top center

Shape can be either circle or ellipse. If no shape is supplied, if the length value is single, it defaults to a circle with a radius defined by that length. Otherwise, if no shape is supplied and two lengths are passed, it uses those to draw an ellipse. The first value determines the width, the second the height:

// A vertical ellipse:
background-image: radial-gradient(center, 100px 400px, red, white);
// An horizontal ellipse:
background-image: radial-gradient(center, 400px 100px, red, white); 

If you use one of the shape keywords, you can also use size keywords to control how the radial gradient is draw in relation to its container. The size keywords are:

– closest-side
– farthest-side
– closest-corner
– farthest-corner

First of all, these keywords only work when you use a shape keyword. Defining the shape of the radial gradient with lengths and then trying to use these size keywords will not work. So, this is how these size keywords work. If the container is narrower than it is tall, the size of circle or ellipse will be restrained by the left and right of the container. With farthest-side, it would be restrained by the top and bottom of the container, probably resulting in the left and right extending beyond those sides. Be aware that these work in relation to the position of the radial gradient. That means that if it is positioned near the top left, it will be rendered differently than if it were centered. Closest-corner and farthest-corner work just like closes-side and farthest-side. The best way to get the hang of these keywords is to play around with a radial gradient to see how they affect it. Although these keywords are nice conveniences, you’ll see that they are far from exact. If you need precise placement and size, you’re better off using lengths to define the size of your radial gradient.

Color and stops work similar to linear gradients. The first color defined the color drawn from the center of the radial gradient. The last color will define the outermost color of the gradient. Stops allow you to define more precise positioning of those colors in the radial gradient.

Repeating Radial Gradients

Like repeating linear gradients, it is possible to create the same effect as a repeating radial gradient. You’d just need to define it tediously repeating the colors and providing appropriate stops. In contrast, using the repeating-radial-gradient function makes this easy.

Practical Examples

Enough with theory. Let’s look at what we can do with linear and radial gradients. By layering them and controlling their size and positioning, we can create complex patterns that we can use as Web assets. Please note that in all of the following examples I’m presenting the gradients without vendor prefixes. To have them render in a browser that currently supports CSS gradients, you would need to provide the appropriate vendor prefix for that browser. When the current spec reaches recommendation status, browser vendors will drop their prefix.

In most of these examples I’ve used a transparent gray. This was so I could just add an background color to show through the transparency. Having the color controlled by the background color makes it easy to change the feel of the pattern.

Here’s a vertical stripe with the transparent gray stripe is separated by a 1 pixel transparent stripe:

background-image: 
   linear-gradient(0deg, 
      rgba(0,0,0,0.1) 75%, 
      transparent 75%);
background-size: 5px 100%;

vertical stripes gradient

Here’s the same stripe horizontal:

background-image: 
   linear-gradient(90deg, 
      rgba(0,0,0,0.1) 75%, 
      transparent 75%);
background-size: 100% 5px;

horizontal stripes gradient

And here it is slanted to the left:

background-image: 
   linear-gradient(45deg, 
      transparent 15%,  
      rgba(0,0,0,0.1) 15%, 
      rgba(0,0,0,0.1) 50%, 
      transparent 50%, 
      transparent 65%,
      rgba(0,0,0,0.1) 69%);
background-size: 6px 6px;

gradient of stripes slanting left

And then to the right:

background-image: 
   linear-gradient(-45deg, 
      transparent 15%,  
      rgba(0,0,0,0.1) 15%, 
      rgba(0,0,0,0.1) 50%, 
      transparent 50%, 
      transparent 65%,
      rgba(0,0,0,0.1) 65%);
background-size: 6px 6px;

gradient of stripes slanting right

Now lets have some fun with repeating linear gradients. Here’s vertical repeating stripes:

background-image: 
   repeating-linear-gradient(0deg, 
      rgba(0,0,0,0.1) 0px, 
      rgba(0,0,0,0.1) 5px, 
      transparent 5px, 
      transparent 10px);

repeating vertical stripes gradient

Horizontal repeating stripes:

background-image: 
   repeating-linear-gradient(90deg, 
      rgba(0,0,0,0.1) 0px, 
      rgba(0,0,0,0.1) 5px, 
      transparent 5px, 
      transparent 10px);

repeating horizontal stripes gradient

Left slanted repeating stripes:

background-image: 
   repeating-linear-gradient(45deg,
      rgba(0,0,0,0.1) 0px, 
      rgba(0,0,0,0.1) 5px, 
      transparent 5px, 
      transparent 10px);

repeating gradient of left leaning stripes

Right slanted repeating stripes:

background-image: 
   repeating-linear-gradient(-45deg,
      transparent, 
      transparent 5px, 
      rgba(0, 0, 0, 0.1) 5px, 
      rgba(0, 0, 0, 0.1) 10px);

repeating gradient of right leaning stripes

Now lets cross them:

background-image: 
   repeating-linear-gradient(0deg, 
      transparent 0,
      transparent 5px, 
      rgba(0, 0, 0, .1) 5px, 
      rgba(0, 0, 0, .1) 10px),
   repeating-linear-gradient(90deg, 
      transparent 0,
      transparent 5px, 
      rgba(0, 0, 0, .1) 5px, 
      rgba(0, 0, 0, .1) 10px);

checkered

And now criss-cross them:

background-image: 
   repeating-linear-gradient(-45deg,
      transparent, 
      transparent 5px, 
      rgba(0, 0, 0, 0.1) 5px, 
      rgba(0, 0, 0, 0.1) 10px),
   repeating-linear-gradient(45deg,
      transparent, 
      transparent 5px, 
      rgba(0, 0, 0, 0.1) 5px, 
      rgba(0, 0, 0, 0.1) 10px);

intersect

Enough with stripes, let’s get square:

background-image: 
   linear-gradient(180deg, 
      rgba(0,0,0,0.05) 75%, 
      transparent 75%),
   linear-gradient(90deg,  
      rgba(0,0,0,0.05) 75%, 
      transparent 75%);
background-size: 5px 100%, 100% 5px;

cubes

And a nice checkerboard pattern:

background-image: 
   linear-gradient(45deg, 
      rgba(0,0,0,0.1) 4.5px, 
      transparent 5px, 
      transparent 16px, 
      rgba(0,0,0,0.1) 16px, 
      rgba(0,0,0,0.1)), 
   linear-gradient(45deg, 
      rgba(0,0,0,0.1) 4.5px, 
      transparent 5px, 
      transparent 16px, 
      rgba(0,0,0,0.1) 16px, 
      rgba(0,0,0,0.1));
background-position: 0 0, 8px 8px;

squares

And let’s make those diagonal:

background-image: 
   linear-gradient(45deg, 
      rgba(0,0,0,0.1) 25%, 
      transparent 25%),
   linear-gradient(-45deg, 
      rgba(0,0,0,0.1) 25%, 
      transparent 25%),
   linear-gradient(45deg, 
      transparent 75%, 
      rgba(0,0,0,0.1) 75%),
   linear-gradient(-45deg, 
      transparent 75%, 
      rgba(0,0,0,0.1) 75%);
background-size: 10px 10px;

chess

Now that we have them diagonal, lets spice them up and turn them into an argyle pattern:

background-image: 
   linear-gradient(right top, 
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 50%, 
      transparent 50%, 
      transparent),
   linear-gradient(left top, 
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 50%, 
      transparent 50%, 
      transparent);
background-size: 12px 12px;

argyle

OK, now lets take another look at stripes. But this time we want to shake things up about. We want to get out to the monotony of strictly repeating patterns, but still have a pattern. What I’m talking about is sometimes called the Cicada principle. It produces a pattern that doesn’t repeat itself exactly. It does this my layering different repeating patterns, except that these are different proportions, similar to the progression of prime numbers. Using this principle, I’ve created a series of overlapping lines that creates a textile like pattern that retains it’s randomness. Here’s the CSS:

background-image: 
   linear-gradient(left, 
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 25%, 
      transparent 25%, 
      transparent),
   linear-gradient(left, 
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 15%, 
      transparent 15%, 
      transparent),
   linear-gradient(left, 
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 15%, 
      transparent 15%, 
      transparent),
   linear-gradient(top, 
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 17%, 
      transparent 17%, 
      transparent),
   linear-gradient(top,
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 15%, 
      transparent 15%, 
      transparent),
   linear-gradient(top,
      rgba(0,0,0,0.1), 
      rgba(0,0,0,0.1) 13%, 
      transparent 13%, 
      transparent);
background-size: 10px 100%, 17px 100%, 21px 100%, 100% 10px, 100% 17px, 100% 21px;
backgroud-position: 0 0, 6px 0, 14px 0, 0 0, 0 6px, 0 16px;

linen

Now lets play with radial gradients. We’ll start with basic patterns and build up to more complex combinations.

background-image:
   radial-gradient( 
      rgba(0,0,0,0.1),
      rgba(0,0,0,0.1) 45%,
      rgba(0,0,0,0) 50%,
      rgba(0,0,0,0) 95%);
background-size: 8px 8px;

speckeled

Now we’ll take the above pattern and turn the dots inside out so that the pattern looks like someone cut holes in the color.

background-image:
   radial-gradient( 
      rgba(0,0,0,0),
      rgba(0,0,0,0) 50%,
      rgba(0,0,0,0.1) 55%,
      rgba(0,0,0,0.1) 95%);
background-size: 10px 10px;

spotted

Now we’ll just play with the size of circles a bit.

background-image:
   radial-gradient( 
      rgba(0,0,0,0.1),
      rgba(0,0,0,0.1) 9px,
      rgba(0,0,0,0) 9px,
      rgba(0,0,0,0) 17px);
background-size: 18px 18px;

circles

OK, I now the above patterns are not revolutionary or anthing. Now we’re going to get creative. For the next ones we’re going to user colors, yeah! The next pattern has a gold background with orange and greenish polka dots:

background-image:
   radial-gradient( 
      rgba(255,0,0,0.2),
      rgba(255,0,0,0.2) 4px,
      rgba(255,255,255,.10) 5px,
      rgba(255,255,255,.10) 7px),
   radial-gradient( 
      rgba(0,0,0,0.2),
      rgba(0,0,0,0.2) 4px,
      rgba(255,255,255,.25) 5px,
      rgba(255,255,255,.25) 7px);
background-size: 18px 18px;
background-color: #ffd239;
background-position: 10px 10px, 0% 0%;

gold-polka-dots

The next one I call puff balls because of their look:

background-image:
   radial-gradient(
      rgba(255,255,255,0) 90%,
      rgba(255,255,255,.5) 90%,
      rgba(255,255,255,.5)
   ),
   radial-gradient( 
      rgba(255,255,255,0.01),
      rgba(255,255,255,0.01) 10%,
      rgba(255,255,255,255.1) 70%,
      rgba(0,0,0,0) 79%,
      rgba(0,0,0,0) 96%);
background-size: 20px 20px;
background-color: #ff77a1;

puff-balls

Here’s another gold pattern with four-pointed stars:

background-image:
   radial-gradient( 
      rgba(255,0,0,0.2),
      rgba(255,0,0,0.2) 8.5px,
      rgba(255,255,255,.5) 9.5px,
      rgba(255,255,255,.5) 17.5px),
   radial-gradient( 
      rgba(0,0,0,0.2),
      rgba(0,0,0,0.2) 8.5px,
      rgba(255,255,255,.15) 9.5px,
      rgba(255,255,255,.15) 17.5px);
background-size: 18px 18px;
background-color: gold;
background-position: 9px 9px, 0% 0%;

gold stars

And here we change the background to green:

background-image:
   radial-gradient( 
      rgba(255,210,57,0.42),
      rgba(255,210,57,0.42) 9px,
      rgba(0,0,0,0) 11px,
      rgba(0,0,0,0) 15px),
   radial-gradient( 
      rgba(0,0,0,0),
      rgba(0,0,0,0) 9px,
      rgba(255,210,57,1) 10px,
      rgba(255,210,57,1) 15px);
background-size: 17px 17px;
background-color: #1e8e04;
background-position: 8.5px 8.5px, 0% 0%;

green stars

And finally, we do some interesting overlap with the radial gradients:

background-image:
   radial-gradient( 
      rgba(255,255,255,0),
      rgba(255,255,255,0.5) 14px,
      rgba(255,255,255,0) 14px,
      rgba(255,255,255,0) 26px),
   radial-gradient( 
      rgba(0,0,255,0.31),
      rgba(0,0,255,0.31) 14px,
      rgba(255,255,255,0) 16px);
background-size: 28px 28px, 28px 28px;
background-position: 14px 18px, 0% 18px, 0% 0%;
background-color: rgba(200,250,190,0.5);

petals

You can see these gradients in action here. You can same the page to your desktop, since it is a self-contained document.

Proposed Changes to Spec

So, as I mentioned, since January 2012 the draft for CSS gradients at the W3C has some notation changes. Really their minor, but in my opinion, not necessary. Actually, I’m irritated by them. The two owners of the document: Elika J. Etemad and Tab Atkins Jr., from Mozilla and Google respectively, have decided to make the notation more English-like by requiring prepositions for the position keywords for linear and radial gradients. So if you had a yellow to red linear gradient that ended in the bottom right, you’d need to write the following:

linear-gradient(to bottom right, yellow, red);

For a radial gradient, it would be

radial-gradient(circle at closest-side, yellow, red);

OK, so if the point is to make it more English-like, shouldn’t it be:

linear-gradient(to the bottom right, yellow, red)

Or better yet:

linear-gradient(directed toward the bottom right, yellow, red);

Or:

radial-gradient(a circle positioned at closest-side, yellow, red);

And, last time I check, a big chuck of the world doesn’t know what the English word “to” means and so it adds no clarity to what the keywords are doing. I’m totally against requiring unnecessary English grammatical constructs in to CSS. We don’t do that with HTML or JavaScript. What strikes me as really odd, one of the authors is from Mozilla. They were the guys that complained that the original Webkit notation used “to” and “from” to designate the start and end colors. Now they want to make the simpler notation more complicated. Adding prepositions to keywords for gradients will not add any new functionality nor prevent any rendering errors. They just make the notation more wordy. Fail! Making CSS more English-like is a rabbit hole down which you do not want to go.

March 23, 2012

Since writing this post there has been some ongoing discussion at CSS Working Group about the reasoning behind the use of prefixes in the new syntax. The gist of it is that prepositions actually remove the ambiguity of direction when dealing with gradients. Here’s a quote from the discussions:

The “to” keyword was added to linear gradients because there was
significant confusion about whether “top” meant “start from the top
(put the 0% color on the top)” or “point toward the top (put the 100%
color on the top)”.

Radial gradients gained keywords in an attempt to make the syntax more
flexible and more readable – previously, for example, you could have a
declaration like “radial-gradient(20% 20%, 30% 30%, black, white)”.
It’s very unclear what that means – even if you know that one of them
is a position and the other is a size, how can you tell which is
which? Due to this ambiguity, the syntax also disallowed specifying
just a size without a position.

The new syntax, while not ideal in some ways, solves this problem –
you’d write the previous example as “radial-gradient(30% 30% at 20%
20%, black, white)” which gives you some clues as to which is the size
and which is the position. As well, it’s now possible to specify
either a size or a position alone, and have it parsed unambiguously –
“radial-gradient(30% 30%, black, white)” has an explicit size and
default position, while “radial-gradient(at 20% 20%, black, white)”
has an explicit position and default size.

In light of the above I’ve been won over to support prepositions in the gradient syntax. It solves the problems described above and will make creating gradients easier for everyone.

Back and Next Buttons Revisited

So, many moons ago, I wrote a post about how to make iOS style “Back” and “Next” buttons using CSS. Only problem was that technique used a span tag to create the pointer. For some reason it slipped my mind that I could use the CSS generated content property with the :before pseudo-element. Rather than being bothered with having to stick spans into buttons to turn them into pointers, I now introduce you to a more sane method of creating “Back” and “Next” buttons with just CSS.

Now you might be wondering how we would generate the node we need to style as a pointer. Using the CSS content property we can generate automatic content inside the button, removing the necessity of having a tag sitting there for no other reason. Unfortunately the content property only generates alpha-numeric content. We can’t use it to create a span or any other tag. But we don’t have to use a normal character as the content. A space will suffice to create the desired pointer. We make it display as a block element and then style it as if it were a normal pointer. Problem solved.

To accomplish our goal we need to switch out any reference to < span.pointer for :before

So, here’s the styles for a normal button, followed by the styles for the pointer.


.button.bordered.back:before {
	content: " ";
	display: block;
	z-index: 0;
	background-image: 
		-webkit-gradient(linear, left top, right bottom, 
			from(#92a1bf), 
			color-stop(0.3, #798aad),
			color-stop(0.51, #6276a0), 
			color-stop(0.51, #556a97), 
			color-stop(0.75, #566c98),
			to(#546993)); 
	border-left: solid 1px #484e59;
	border-bottom: solid 1px #9aa5bb;
	-webkit-border-top-left-radius: 5px;
	-webkit-border-bottom-right-radius: 5px;
	-webkit-border-bottom-left-radius: 4px;
	height: 23.5px;
	width: 23.5px;
	display: inline-block;
	-webkit-transform: rotate(45deg);
	-webkit-mask-image: 
		-webkit-gradient(linear, left bottom, right top, 
			from(#000000), 
			color-stop(0.5,#000000), 
			color-stop(0.5, transparent), 
			to(transparent));
	position: absolute;
	left: -9px;
	top: 2.5px;
	-webkit-background-clip: content;
}
.button.bordered.back:hover:before, .button.bordered.back.touched:before {
	background-image: 
		-webkit-gradient(linear, left top, right bottom, 
			from(#7d88a5), 
			color-stop(0.3, #58698c),
			color-stop(0.51, #3a4e78), 
			color-stop(0.51, #253c6a), 
			color-stop(0.75, #273f6d),
			to(#273f6d)); 
}

You can check out the finished version online or download the source code.

ChocolateChip-UI

Learn more about ChocolateChip-UI

ChocolateChip.js is now ChUI (pronounced “chewy”)

In the course of time I’ve created a lot of POCs (proof of concepts) on this blog. Some where fairly good, some where flaky one-offs. In the process I also created a small JavaScript library — ChocolateChip.js — that I used for actualizing most of these demos. Seeing how many people come to this humble blog in search of solutions to their development projects, I though about taking all the good ideas in these demos and putting them together as a one stop solution for mobile Web app development. I’m therefore today announcing ChocolateChip-UI. At present it’s a beta, but I intend to keep developing it to add more useful features over time. I

ChocolateChip-UI consists of ChocolateChip.js plus two other files: ChUI.js and ChUI.css. ChUI.js is a collection of JavaScript methods built on top of ChocolateChip.js. ChUI.js provides controls and widgets enlivened with behaviors needed for Web app development. ChUI.css is the magical CSS that makes simple markup look and act in a amazing way.

ChocolateChip-UI also introduces a new concept: WAML (Web App Markup Language). This is a specialized set of tags and attributes that get around the limits of HTML. HTML tags are really about creating documents, like books and other text publications. In contrast, WAML is a collection of tags and attributes that make sense for Web app development. ChUI.js and ChUI.css are built around the implementation of WAML as the key to how ChocolateChip-UI works.

WAML takes the paradigms of mobile application development and transfers those over to the development of mobile Web apps. There’s no need to smother and bury HTML tags with tons of classes trying to make markup meant for publishing documents work for creating applications. At the same time, WAML is really just a superset of HTML5 markup. You can therefore use any HTML5 tags and attributes along with WAML and ChocolateChip-UI to implement your solution.

ChocolateChip-UI is about making Web app development more straightforward. It provides common controls which have built in functionalities. Instead of having to figure out how to build these yourself, you can spend that time providing the data you want through ChocolateChip-UI’s controls easy to use controls.

The interfaces and controls which ChocolateChip-UI provides are all created using only markup and CSS. No images are required, no gifs or pngs. This means that everything you build with ChocolateChip-UI will be resolution independent. It will look good on a handheld mobile device and on a big HDMI screen. ChocolateChip-UI also provides a set of 52 SVG icons for use with buttons. Because these are vector based, they too are resolution independent. ChocolateChip-UI is therefore the first resolution independent mobile Web app framework.

The Holy Grail of Mobile Layout

The Holy Grail of Mobile Layout

The perfect mobile layout should allow the presence of a navbar, a content area and maybe a footer toolbar. This layout should resize with orientation changes such that the bottom toolbar is always at the bottom and the content area resizes its width and height to fit the new dimensions. This is tough because, first off, there is not fixed positioning, and secondly, there is no single finger scrolling in Webkit for CSS defined scrolling regions.

it’s taken me a while to come up with a solution to these layout requirements. Any of you trying to make a Web app feel like a native mobile app know the frustration of trying to deal with orientation change and complex layout. Not being able to make a toxic mix of viewport meta tags, CSS media queries and onorientationchange events work to give me a fluidly resizing layout when the mobile device’s orientation changed drove me to despair. I compensated early on using JavaScript to resize everything, except I had to pay a performance penalty, especially if an app was complex. After a lot of sweat and blood and endless trial and error, I finally came up with a CSS only solution to making a layout that resizes smoothly with orientation changes.

So, the first big mistake, one that everyone and their brother recommends, is not to use the meta tag viewport settings of device width and device height. Instead, just use the initial scale, maximum scale and user scalability:

<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

The reason is that no matter what you set the width and height to with CSS, Webkit insists on thinking the document should have the height and width from when the document first loaded. This happens even if you use a CSS value of “width: 100%”. Switching from portrait to landscape, you’ll see that your layout fails to fill the width of the landscape screen:

iPhone Portrait Layout

iPhone Portrait Layout

iPhone Landscape Layout

iPhone Landscape Layout

As you can see with the landscape orientation the layout fails to fill the available width of the device. This app has its root elements’ widths set to 100% and a meta tag of:

<meta name="viewport" content="width=device-width; height=device-height; initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

Removing the device width and height from the meta tag will give us the fluid layout we seek:

<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

With the above change, when switching this document loaded in portrait orientation to landscape mode orientation we get a resized document the way we would like:

iPhone Landscape Layout Correctly Resized

iPhone Landscape Layout Correctly Resized

OK, so we have a navbar on the top, but what if we want a toolbar on the bottom? No problem. We can accomplish that with a few adjustments. To fix the toolbar to the bottom we’ll use absolute positioning. One thing to remember about this layout technique, if you are going to have navbars or toolbars, you’ll need to adjust the height of the content so that it fits the space left over by the bars. I do this using a class or class on the content section. A navbar or toolbar has a default height of 45 pixels, so you’d want to position your content that distance from a navbar or toolbar. To make this work, we’re going to have to use absolute positioning on the content section and on any bottom toolbar. One thing rather frustrating about using absolute positioning on block elements is that it causes them to collapse to what their content is, even with they have a width of 100%. We can get around this by setting the appropriate side to 0 pixels. For a bottom toolbar this could be something like this:

.toolbar.bottom {
    height: 45px;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
}

With the above measurement, we have a toolbar that is 45px high fixed to the bottom and stretching from side to side. This toolbar will maintain these dimensions and placement even with an orientation change. We’ll need to do something similar for the content area. Like I said, we’ll need to use absolute positioning and account for any space taken up by a nav or toolbar. I use classes to do this, such as “withNavbar”, or “withNavbar withBottomToolbar”, or “withBottomToolbar”. The CSS for these classes would be something like this:

/* Definition for content area that fills the screen: */
#content {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
#content.withNavbar {
    top: 45px;
    right: 0;
    bottom: 0;
    left: 0;
}
#content.withBottomToolbar {
    top: 0;
    right: 0;
    bottom: 45px;
    left: 0;
}
#content.withNavbar.withBottomToolbar {
    top: 45px;
    right: 0;
    bottom: 45px;
    left: 0;
}

We also need to make sure that the document’s content doesn’t bleed down below the bottom toolbar. We do this by wrapping the entire document in a div. I give it an id of #main:

<body>
	<div id="main">
		<div class="navbar">
			<h1>The Title</h1>
		</div>
		<div id="content" class="withNavbar withBottomToolbar">
			<ul class="table-view">
				<li><span class="title">Item One</span></li>
				<li><span class="title">Item Two</span></li>
				<li><span class="title">Item Three</span></li>
				<li><span class="title">Item Four</span></li>
				<li><span class="title">Item Five</span></li>
				<li><span class="title">Item Six</span></li>
				<li><span class="title">Item Seven</span></li>
				<li><span class="title">Item Eight</span></li>
			</ul>
		</div>
		<div class="toolbar placement-bottom">
			<div class="button">Edit</div>
			<div class="button">Save</div>
		</div>
	</div>
</body>

The styles for the div#main would be:

#main {
	width: 100%;
	display: -webkit-box;
	margin: 0 0 0 0;
	padding: 0;
	height: 100%;
	-webkit-box-orient: vertical;
	-webkit-box-align: stretch;
	-webkit-box-sizing: border-box;
	-webkit-transition: all 0.25s  ease-in-out;
	overflow: hidden;
	position: absolute;
	top: 0;
	left: 0;
	bottom: 0;
	right: 0;
}

Although the above arrangement solves the layout problems for mobile interfaces with automatic adjustment with orientation changes, it presents a new problem. That’s the problem of making the data in the content area reachable by the user. You’ll need to add a way for the user to scroll just that area. Normally the whole document would scroll with the browser, with the result that the top part would scroll out of view. Since we’ve fixed the toolbar to the bottom and have the height of the content area control by absolute position affecting its top, right, bottom and left, we need to provide a way to enable scrolling. Actually we could do this very simply using the CSS overflow property: #content { overflow-y: auto; }. However, on mobile Webkit this requires a two finger gesture. Most users would not expect this. They’ll use a single finger and think that the content is not scrollable.

There’s a simple way to provide single finger scrolling with a JavaScript module called “iScroll” created by Matteo Spinelli. This is a great implementation which provides deceleration animation of the scrolling, just like iOS, Android and other mobile OSes. One thing to be aware of when using iScroll, you don’t use it directly on the content container as this would cause that contain to slide up and down over the navbar and toolbar. Instead you’ll need to add an extra div tag inside it and use iScroll on that. iScroll will then enable scrolling of the div inside the content div. There are a number of options, my favorite is for desktop simulation. Here how you would do it:

<div id="content" class="withNavbar withBottomToolbar">
    <div id="scrollwrapper">
        <!-- Content In Here -->
    </div>
</div>
.........

<script type="text/javascript">
    var scroller = new iScroll(’scrollwrapper’, { desktopCompatibility : 
        true });
</script>

This gives you a basic mobile Web interface with a top navbar, a bottom toolbar and a content area with scroll that resizes quickly with orientation change.

Since publishing this article, I’ve created a framework for creating mobile Web apps. It uses many of the techniques explored in my blog posts. You can learn more about the framework by visiting ChocolateChip-UI.com. There are demos you can try in your desktop browser or on your mobile device.

CSS Gradients for IE9

This works with Desktop IE9, Desktop Firefox, Desktop Chrome, Desktop Safari, Desktop Opera, iOS, and Android.

Attention! IE9 will not destroy the world, kill babies, or take away your home or job.

Simply put, IE9 is the best browser Microsoft has ever released. Has it caught up to Chrome, Firefox and Safari? No. But that doesn’t matter. It’s still light years ahead of any other version of IE. All of us should be praying every day for IE users to upgrade to it as soon as possible.

Shortly after the initial launch of the beta of IE9, I began testing to see what kind of support it had for all the rich and exciting features CSS3 offers for Web layout and interaction. The earlier beta’s didn’t have much, but with each release it has gotten better. If you’re already using advanced CSS3 for Web development and never bothered supporting IE before, you’ll want to know what it supports and what it doesn’t. Here’s what it supports at present right from the horse’s mouth. In particular, it supports real CSS opacity, multiple background images, box shadows, border radius, background-clip, background-size, background-position, WOFF for Web fonts, RGBA and HSLA color, box sizing, as well as the full suite of CSS3 selectors. The above post also talks about support for CSS3 2d transforms, however, even with the -ms- vender prefix I am unable to get it to work with the present beta (7).
Update: Transforms are working in Platform Preview 6, which is different from the present public beta. Microsoft is taking a two track approach to releasing this: the public beta for general users to test and a platform preview where features are introduced but not necessary finalized.

So what didn’t make it into IE9? First up, the flexible box model. Once you’ve used the flexible box model for layout, it’s as painful as eating glass to go back to using floats and positioning for layout. No text shadow, which is a strange omission considering they have box shadow. No border images. No CSS transitions. The single-threaded nature of JavaScript makes it inefficient for complex animations. Offloading style animations to the browser’s CSS rendering engine frees up JavaScript and allows the browser to use threads and hardware acceleration for better optimization. In my opinion, CSS3 transitions are more important than CSS3 transforms. Since Firefox, Opera and Webkit all support CSS3 transitions to some degree, it’s a odd omission for IE9. No 2d or 3d transforms. As I mentioned before, transforms do not appear to be implemented in the current beta. (Someone correct me if I’m wrong on this.) The thing I love about CSS3 transitions and transforms is that they allow you to create user interactions that make a Web application feel like a native one, blurring the difference between desktop and Web. No CSS3 keyframe animation. If you thought CSS3 transitions were awesome, you be blown away by CSS keyframe animations.

When I look at IE9’s support for CSS3, it appears they decided to pick the low hanging fruit: border radius, drop shadow, multiple backgrounds, etc. But the flexible box model, gradients, transitions, transforms and keyframe animation are the things in CSS3 that really turn your head.

I have no experience working with Adobe Flash. I do have extensive experience working with Microsoft’s Silverlight platform. I love how it enables you to create rich, interactive user interfaces where you can customize every aspect of a control’s look and feel. Chrome, Firefox and Safari’s support for CSS3 enables a similar high level of possibilities for the creation of Web user interfaces. IE9 is attempting to achieve feature parity with the other browsers and is making good progress. But if you want to use the CSS3 features that IE9 doesn’t support, you’ll need to find workarounds.

Presently my main area of focus is the mobile Web on Android, Blackberry 6, iOS and WebOS. That’s a world ruled by Webkit. But I usually make efforts to ensure that my solutions can also work with modern desktop browsers: Chrome, Firefox and Safari. That involves a lot of vender prefixes: -moz, -webkit. And then you need to future proof it by supplying the same property without the vendor prefix. This technique allows browsers that understand the properties, like IE9, to also render them without any extra effort.

I’m going to take one example of an HTML/CSS3 implementation of iOS’s popup dialog box which I originally created for use on iOS devices and show how I got it to render equally in Chrome, Firefox, IE9, Opera and Safari. At the end of this post you’ll find links to try it out online or download it. One thing, I’m not using any image pieces, just CSS3 properties. Here’s the initial state of the page with the popup in Safari and Firefox:

popup Initial state

Here’s the page with the popup in view in Safari and Firefox:

Here’s the same markup in IE9. Notice how it understands border radius, box shadow and RGBA background color, but cannot render the flexible box model layout nor the CSS3 gradients.

ie9 initial state no styleie9 final state no style

IE9’s lack of support for the flexible box model can be resolved by using old-school layout techniques (floats/positioning). But there is no way to fake CSS3 gradients with pngs. When you stretch them they exhibit banding. Since I make extensive use of CSS3 gradients all the time, I felt pressed to find a solution for IE9. After spending some time experimenting with SVG in IE9, I hit on an idea. Using an IE9 specific stylesheet, I would try setting SVG gradients as background images on the element’s that use CSS3 gradients. The technique works quite well. Here’s IE9 with its custom CSS:

ie9 initial state fixedie9 final state fixed

First, here’s a CSS3 gradient used by Chrome, Firefox and Safari:

header {
	width: 100%;
	display: -webkit-box;
	display: -moz-box;
	display: box;
	-webkit-box-orient: horizontal;
	-webkit-box-pack:justify;
	-webkit-box-align: center;
	-webkit-box-sizing: border-box;
	-moz-box-orient: horizontal;
	-moz-box-align: center;
	-moz-box-pack:justify;
	-moz-box-sizing: border-box;
	box-orient: horizontal;
	box-align: center;
	box-pack:justify;
	box-sizing: border-box;
	height: 45px;
	margin: 0;
	padding: 0 10px;
	background-image: 
		-webkit-gradient(linear, left top, left bottom, 
			from(#b2bbca), 
			color-stop(0.25, #a7b0c3),
			color-stop(0.5, #909cb3), 
			color-stop(0.5, #8593ac), 
			color-stop(0.75, #7c8ba5),
			to(#73839f)); 
	background-image: 
		-moz-linear-gradient(top,
			#b2bbca, 
			#a7b0c3 25%,
			#909cb3 50%, 
			#8593ac 50%, 
			#7c8ba5 75%,
			#73839f); 
	border-top: 1px solid #cdd5df;
	border-bottom: 1px solid #2d3642; 
}

As you can see in the above code, we’re defining background images as gradients with a number of color stops. That all a CSS3 background gradient is. As a matter of fact, it’s rendered by the browser as a canvas background image. Since IE9 supports SVG, including as background images, I’ve come up with a way to use SVG gradient images as background gradients. Because SVG is vector-based, the gradients scale without banding. SVG is an XML markup language for describing vector graphics. The HTML5 parsing engine allows SVG to be directly embedded in HTML. But I want background images. By defining the height of the SVG document as 100%, I have an image that will scale to whatever the element is, just like the CSS3 gradient. Here’s the markup that I used to create the gradient for the header. Notice that the SVG gradient has color-stops and offsets like the CSS gradients. They aren’t that different.

<?xml version="1.0" ?>
<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" version="1.0" width="100%" 
   height="100%" 
     xmlns:xlink="http://www.w3.org/1999/xlink">

  <defs>
    <linearGradient id="myLinearGradient1"
                    x1="0%" y1="0%"
                    x2="0%" y2="100%"
                    spreadMethod="pad">
      <stop offset="0%"   stop-color="#b2bbca" stop-opacity="1"/>
      <stop offset="50%"   stop-color="#909cb3" stop-opacity="1"/>
      <stop offset="50%"   stop-color="#8593ac" stop-opacity="1"/>
      <stop offset="100%" stop-color="#73839f" stop-opacity="1"/>
    </linearGradient>
  </defs>

  <rect width="100%" height="100%"
     style="fill:url(#myLinearGradient1);" />
</svg>

The document has a height and width of 100%, the gradient is set to expand to 100% and the rectangle is defined with a height and width of 100%. It is possible to turn this SVG image into a datauri and put it directly in the CSS, using use any of the many resources available for datauri conversion. However, the SVG files are just simple text files. If you convert them to datauris, you will not be able to make any changes to them. While putting this demo together I had to constantly tweak the values in the SVG gradients to get them exact. Keeping the SVG files allows you to go back and modify the gradients at any time. Here’s how you use this for IE9:

header {
  background-image: url("svg-gradient.svg");
}

That’s it. IE9 will display the above SVG graphic in a manner indistinguishable from native CSS3 gradients.

For the repeating striped background gradient on the body tag, I’m using a CSS3 gradient with background sizing and letting it repeat across the page. For IE9 I do the same thing, using background sizing on the SVG equivalent to get the same effect.

Like IE9, Opera also does not support the flexible box model nor CSS3 gradients. Notice how Opera renders the demo basically the same as IE9:

Opera initial state no styleOpera final state no style

After creating the SVG workaround for IE9 to mimic CSS3 gradients, I started thinking about Opera’s lack of support for CSS3 gradients. Opera has the best support for SVG out of all the browsers. I therefore tried giving Opera the same CSS that I gave IE9. It worked as well as it did for IE9. You can see the results below:

Opera inital state fixedOpera final state fixed

There is very minimal browser sniffing required to make this work across modern browsers. One stylesheet for Chrome, Firefox and Safari, a conditional comment for IE9 and a browser agent sniff for Opera:

<!--[if IE 9]>
	 <link rel="stylesheet" type="text/css" href="popup-svg.css">
<![endif]-->

<script type="text/javascript">
    var Opera = /opera/i.test(navigator.userAgent);
    if (Opera) {
        var link = document.createElement("link");
        link.setAttribute("rel", "stylesheet");
        link.setAttribute("href", "popup-svg.css");
        document.getElementsByTagName("head")[0].appendChild(link);
}
</script>

Please Note: If you’re going to use this technique in a production environment you should use feature detection because at some point Opera will support CSS gradients. There are a number of ways to accomplish feature detection. Perhaps the easiest is to use Modernizr.

You can try out this demo online or download the source code. Feel free to use the included SVG files as templates for your own gradients.

Oh, and one last thing. I’m using the ChocolateChip mobile JavaScript framework for this demo. Originally I created it to work on mobile devices using Webkit browsers. I therefore provided no support for the JScript quirks of IE. But since IE9 has a completely rewritten JavaScript engine and uses the standard event model and DOM interfaces like the other browsers, ChocolateChip works fine on it without modification. That definitely put a smile on my face.

Making an iPhone Switch Control without Images

Works on desktop Safari, Chrome and Firefox, iPhone, iPod Touch and iPad.

On the iPhone and iPad, Apple uses a control called switch. It’s actually a different take on the checkbox. Like radio buttons, checkboxes do not lend themselves to touch interfaces, especially guys with fat fingers, cough! Instead of making us suffer with those dinky checkboxes, Apple uses a more visual cue to what the user is actually doing, switching something on or off. As a matter of fact, that’s exactly how the control is labeled: “on” or “off”. They’re really easy to use, just swipe your finger to throw the switch, done. In case you’re not sure what I’m talking about, here they are:

switch control

OK, so all the mobile Web frameworks have a switch control. And I hate them all. They either do an instant switch between the on and off state, using an image sprite, or they do this really lame thing where they animate the horizontal background position of the image on a checkbox with its default styles removed. None of those implementations feels the same as when you swipe the switch control in a native iOS app.

So what am I going to do? I tell you, I’m going to throw the friggin’ image out and build the whole control from scratch using just HTML, CSS3 and some JavaScript to make it work. Bada-bing! To start with, here’s the basic markup for a checkbox:

<div class="checkbox unchecked" id="sleepSwitch">
	<div class="on">ON</div>
	<div class="thumb"><span></span></div>
	<div class="off">OFF</div>
	<input type="checkbox" value="ZZZZZZZZ!" offvalue="But, I need more sleep!">
</div>

As we did when we created iPhone style radios buttons, we’re using real checkboxes in our iPhone switch controls. And like in the radio button example, we’ll set the checkbox input’s display value to “none”. We’ll use CSS3 properties to style the markup to look like a real iOS switch control and we’ll attach event listeners to set the input checkbox’s check state to true or false, depending on whether we want it to be selected or not.

To create this switch control we’ll need to style the frame named “checkbox” with rounded corners. Notice that the markup above contains three parts: the on state, the thumb and the off state. The rounded frame will only be wide enough to show one state plus the thumb. Using CSS3 transitions and transforms, a click or touch will cause the three elements to side back and forth within the rounded frame. For positioning the switch’s elements and sliding them back and forth we’re going to use CSS3 3d transforms on the x axis. Here is the CSS to make this happen:

/* Checkbox */
.checkbox {
	display: -webkit-box;
	-webkit-box-orient: horizontal;
	-webkit-box-pack:justify;
	-webkit-box-sizing: border-box;
	-webkit-tap-highlight-color: transparent;
	width: 94px;
	overflow: hidden;
	-webkit-border-radius: 6px;
	text-align: center;
	line-height: 28px;
	cursor: pointer;
	-webkit-user-select: none;
	position: absolute;
	right: 10px;
	top: 7px;
}
.checkbox > input[type="checkbox"] {
	display: none;
}
.checkbox .thumb {
	-webkit-border-radius: 7px;
	position: relative;
	z-index: 3;
	border: solid 1px #919191;
	-webkit-transition: all 0.125s  ease-in-out;
	-webkit-transform: translate3d(0px,0%,0%);
}
.checkbox .thumb span {
	display: block;
	-webkit-box-sizing: border-box;
	height: 25px;
	width: 38px;
	border-top: solid 1px #efefef;
	-webkit-border-radius: 6px;
	background-image: -webkit-gradient(linear, left top, left bottom, from(#cecece), to(#fbfbfb));
	border-top: solid 1px #efefef;
	position:relative;
}
.checkbox .on {
	color: #fff;
	background-image: 
		-webkit-gradient(linear, left top, left bottom, 
			from(#295ab2), 
			to(#76adfc));
	width: 54px;
	padding-right: 4px;
	border: solid 1px #093889;
	-webkit-border-top-left-radius: 6px;
	-webkit-border-bottom-left-radius: 6px;
	margin-right: -6px;
	height: 25px;
	-webkit-transition: all 0.125s  ease-in-out;
	position: relative;
	-webkit-transform: translate3d(0px,0%,0%);
}
.checkbox .off {
	color: #666;
	background-image: -webkit-gradient(linear, left top, left bottom, from(#b5b5b5), color-stop(0.50, #fff));
	width: 54px;
	padding-left: 4px;
	border: solid 1px #a1a1a1;
	-webkit-border-top-right-radius: 6px;
	-webkit-border-bottom-right-radius: 6px;
	margin-left: -6px;
	height: 25px;
	-webkit-transition: all 0.125s  ease-in-out;
	position: relative;
	-webkit-transform: translate3d(-54px,0%,0%);
}
.checkbox.unchecked .thumb {
	-webkit-transform: translate3d(-54px,0%,0%);
}
.checkbox.checked .thumb {
	-webkit-transform: translate3d(0px,0%,0%);
}
.checkbox.unchecked .on {
	-webkit-transform: translate3d(-60px,0%,0%);
}
.checkbox.checked .on {
	-webkit-transform: translate3d(0px,0%,0%);
}
.checkbox.unchecked .off {
	-webkit-transform: translate3d(-54px,0%,0%);
}
.checkbox.checked .off {
	-webkit-transform: translate3d(6px,0%,0%);
}
/* For Very Important changes, use the orange checkbox */
.checkboxBase.important .on {
	border: solid 1px #d87100;
	background-image: -webkit-gradient(linear, left top, left bottom, from(#e75f00), color-stop(.5, #ff9c12));
}
/* End Checkbox */

To make the switch more realistic, I’m transforming all three pieces of the switch at the same time. This gives the switch a more realistic feeling. Notice the comment in at the end of the above CSS about the important class. You can use this to indicate a switch that makes a very important change. This class changes the default switch’s blue color to bright orange. This is the color Apple uses to show that a switch’s action is very important.

Having the CSS defined for the look and animation brings us close to the finished control, but we need to write some JavaScript to make the switch interactive. The JavaScript needs to do two things: toggle the classes “checked” and “unchecked” on the switch, and toggle the checked value of the checkbox between true and false. I’m using the ChocolateChip JavaScript framework to do this. You can switch my code to whatever library you want. If you know basic JavaScript, it shouldn’t be hard. Here’s the JavaScript to make it happen:

Element.prototype.toggleSwitch = function() {
	if (this.hasClass("switch")) {
		if (this.last().checked === true) {
			this.last().checked = false;
			this.toggleClass("checked", "unchecked");
		} else {
			this.last().checked = true;
			this.toggleClass("checked", "unchecked");
		}
	} else {
		return false;
	}
};

The last() used in the code above is a ChocolateChip method to return the last child of the control, which happens to be the checkbox input. That way we can set its checked state to true or false.

Now that we have the code to setup up the switch control, we can make it work as follows:

$(".switch").forEach(function(checkbox) {
	checkbox.bind("click", function() {
		this.toggleSwitch();
	});
	
	checkbox.bind("touchstart", function(e) {
		e.preventDefault();
		this.toggleSwitch();
	});
}); 

That’s it to make the switch switchable. But to make it do something you’d need a bit more as well. In my example, I’m getting some values from the switch and outputting it to a response field like this:

$(".switch").forEach(function(checkbox) {
	checkbox.bind("click", function() {
		if (this.last().checked === true) {
			$("#switchResponse").fill(
				this.last().getAttribute("value"));
		} else {
			$("#switchResponse").fill(
				this.last().getAttribute("offvalue"));
		} 
	});
	
	checkbox.bind("touchstart", function(e) {
		if (this.last().checked === true) {
			$("#switchResponse").fill(
				this.last().getAttribute("value"));
		} else {
			$("#switchResponse").fill(
				this.last().getAttribute("offvalue"));
		}
	});
}); 

You can try this out online or download the source code.

User Controled Color Theme

Works on Desktop Safari, desktop Google Chrome, desktop Firefox 3.6-4, iPhone, iPod Touch, iPad.

So, in the last blog post I showed how to make RGB slides with HTML, CSS and some JavaScript. I thought about it and, while interesting, it doesn’t have a whole lot of practical application. Sure you could take that and hook up any other type of value to get whatever result you might need for your interface. Well that got me to thinking, so I threw together an implementation of the RGB sliders that allow a user to change the color scheme of a Web app. No need to spend time creating different color themes. Let the user do it.

OK, before you think I’m crazy, especially you folks from the design community, let me explain. I came up with a basic theme technique. I call it chromaeleon &mdash because the app’s chrome can change colors like a chamaeleon. The way this works is, instead of solid color gradients, you create gradients with transparent values of black and white. Behind this you have a background color which shows through the transparent gradients. This way, when the user drags the sliders, the background colors update and the look of the interface changes. Now in the real world you’d want to provide a way for the user to save their color choice. You could save the choice to localStorage. Then when the app loads, it checks to see it the user saved a color choice, if not, it goes to the default. Sorry, I didn’t do all of that. Just the part to update the background colors. Here’s what it will look like:

iPhone Chromaeleon Interface

The structure we’re going to use is pretty must standard as we’ve used elsewhere, a header, a section, some buttons.

<body>
	<header>
		<a href="http://css3wizardry.com" class="button back"><span class="pointer"></span><span>Back</span></a>
		<h1>Chromaeleon Theme</h1>
		<span class="button">Click Here</span>
	</header>
	<section>
		<h2>Use the sliders to adjust the colors of the theme.</h2>
		<div class="colorRow">
			<div id="redSlider" class="slider">
				<div class="thumb"></div>
			</div>
			<div id="redColor" class="colorOutput"></div>
			<span> Red</span>
		</div>
		<div class="colorRow">
			<div id="greenSlider" class="slider">
				<div class="thumb"></div>
			</div>
			<div id="greenColor" class="colorOutput"></div>
			<span> Green</span>
		</div>
		<div class="colorRow">
			<div id="blueSlider" class="slider">
				<div class="thumb"></div>
			</div>
			<div id="blueColor" class="colorOutput"></div>
			<span> Blue</span>
		</div>
		<div class="colorRow finalResult">
			<span>Final Color: </span>
			<div id="rgbColor" class="colorOutput"></div>
			<br />
			<span>RGB: </span><span id="rgbResult">0, 0, 0</span>
			<br />
			<span>HEX: </span><span id="hexResult">#000000</span>
		</div>
	</section>
</body>

So, for the header and the buttons, we need to change their default gradients, as I mentioned above, to have RGBA transparency values. This is my basic gradient:

background-image: 
	-moz-linear-gradient(top, 
		rgba(255,255,255,.5), 
		rgba(30,30,30,.65) 50%, 
		rgba(0,0,0,.7) 50%, 
		rgba(0,0,0,.8)); 
background-image: 
	-webkit-gradient(linear, left top, left bottom, 
		from(rgba(255,255,255,.5)), 
		color-stop(0.5,rgba(30,30,30,.65)), 
		color-stop(0.5, rgba(0,0,0,.7)), 
		to(rgba(0,0,0,.8)));

And for the hover state of the button, we use this gradient:

background-image: 
	-webkit-gradient(linear, left top, left bottom, 
		from(rgba(0,0,0,.1)), 
		color-stop(0.5,rgba(0,0,0,.5)), 
		color-stop(0.5, rgba(0,0,0,.6)), 
		to(rgba(255,255,255,.2)));
background-image: 
	-moz-linear-gradient(top,
		rgba(0,0,0,.1), 
		rgba(0,0,0,.5) 50%, 
		rgba(0,0,0,.6) 50%, 
		rgba(255,255,255,.2));

Now to change the color, all we need to do is introduce a new method to our existing code:

/**
*
* Method to update chrome colors according to the RGB value of the sliders.
*
*/
$.updateInterfaceColors = function() {
	$("header").css("background-color: rgb(" + $.rgbColor[0] + "," + $.rgbColor[1] + "," + $.rgbColor[2] + ")");
	$$(".button").forEach(function(button) {
		button.css("background-color: rgb(" + $.rgbColor[0] + "," + $.rgbColor[1] + "," + $.rgbColor[2] + ")");
	});
	$("section").css("background-color: rgb(" + $.rgbColor[0] + "," + $.rgbColor[1] + "," + $.rgbColor[2] + ")");
	$(".pointer").css("background-color: rgb(" + $.rgbColor[0] + "," + $.rgbColor[1] + "," + $.rgbColor[2] + ")");
};

To execute this method, we invoke it in the slide mouse event handlers for each slider, and for touch-based mobile devices we invoke it in the updateSliderTouch method:

/**
*
* This is for the red slider's mouse interaction, you'd do the same for the green and blue sliders' setup scripts as well.
*/
// Set up three sliders for Red, Green and Blue:
$.slider("#redSlider", { 
	onDrag : function() {
		$("#redSlider").setColorFromSlider("red");
		$.updateInterfaceColors();
	},
	// onDragEnd function necessary to remove hover state off of slider thumb when drag ends.
	onDragEnd : function() {},
	top : -6
});
/**
*
* This is for touch-enabled devices. You invoke the $.updateInterfaceColors() method just once inside the updateSliderTouch method's definition, at the very end.
*/
Element.prototype.updateSliderTouch = function( color ) {
	this.style.left =  curX + 'px'; 
	if (color === "red") {
		$("#" + color + "Color").css("background-color: rgb(" + curX +",0,0)");
		$.rgbColor[0] = curX;
	}
	if (color === "green") {
		$("#" + color + "Color").css("background-color: rgb(0," + curX +",0)");
		$.rgbColor[1] = curX;
	}
	if (color === "blue") {
		$("#" + color + "Color").css("background-color: rgb(0,0," + curX +")");
		$.rgbColor[2] = curX;
	}
	$("#" + color + "Slider").css("-webkit-background-size:" + (curX + 1) + "px 9px, 100% 9px");
	$("#" + color + "Slider").css("background-size:" + (curX + 1) + "px 9px, 100% 9px");
	$("#rgbColor").css("background-color: rgb(" + $.rgbColor[0] + "," + $.rgbColor[1] + "," + $.rgbColor[2] + ")");
	$("#rgbResult").fill($.rgbColor[0] + ", " + $.rgbColor[1] + ", " + $.rgbColor[2]);
	$("#hexResult").fill("#" + $.rgb2hex($.rgbColor[0]) + $.rgb2hex($.rgbColor[1]) + $.rgb2hex($.rgbColor[2]));
	$.updateInterfaceColors();
};

This works great on desktop Safari, Chrome and even Firefox (Yay!), and fine on the iPad. For iPod Touch or iPhone you need to load it in portrait mode. it’s a bit cramped due to the size of the sliders. I needed them to be at least 255px long for the RGB values, and then borders, box shadows and the extra space for the thumbs made them barely fit in the iPhone’s and iPod Touch’s default width. Try hitting the plus icon at the bottom of the browser and save it to you device’s desktop. Then run it from there, you’ll have more vertical space. You can try this out online or download the source code. Enjoy!

Range Slider with CSS and JavaScript

Works on desktop Safari, desktop Chrome, desktop Firefox 3.5 – 4, iPhone, iPod Touch, iPad.

In this post I’m going to show how to make a range slider using HTML, CSS and JavaScript that works with both a mouse and a finger. The mouse-enabled version required a small drag-and-drop JavaScript framework. Fortunately I had already put that together several years back. After spending some time playing around with touch events on mobile Webkit, I was able to come up with a way to implement horizontal dragging for the range slider.
range slider

I’m not going to go into details about my mouse-enable drag-and-drop framework. You can popup it open and read the copious comments in the example. However, I will explain how I implemented the touch-enabled drag for the slider.

The structure for a slider is fairly straightforward. You need a track and a thumb:

<div id="redSlider" class="slider">
	<div class="thumb"></div>
</div>

Since the structure is so simple, you might be wondering how we give it the look. The thumb gets border radius to make it round, along with a box shadow and a background-gradient, including a blue background gradient for hover. The slider track is styled with two background gradients, the bottom-most gradient is the default grey which swans the width of the slider. Layered on top of the same track is a second, bluish gradient. By using CSS3’s background sizing property, we will dynamically resize it as the slider’s thumb is dragged.

Of course, just dragging a slider thumb back in forth is not suck a big deal. I therefore created three sliders implemented as RGB pickers. By dragging each thumb, you add or subtract from a red, green or blue value. Down below you’ll see the final RGB and Hex values.
RGB Slider

Here are the basic styles for the slider:

.slider {
	display: inline-block;
	-webkit-box-sizing: border-box;
	-moz-box-sizing: padding-box;
	box-sizing: padding-box;
	-webkit-box-shadow: 2px 2px 4px #666;
	-moz-box-shadow: 2px 2px 4px #666;
	box-shadow: 2px 2px 4px #666;
	height: 9px;
	width: 277px; 
	padding: 1px;
	-webkit-border-radius: 4px;
	-moz-border-radius: 4px;
	border-radius: 4px;
	background-image: 
		-webkit-gradient(linear, left top ,left bottom,
		   from(#0a3a86),
		   color-stop(.5, #4c8de7),
		   color-stop(.95, #6babf5),
		   to(#0a3a86)),
		-webkit-gradient(linear, left top ,left bottom,
			from(#919191),
			color-stop(.5, #f0f0f0),
			color-stop(.5, #fff),
			color-stop(.95, #fff),
			to(#919191));
	background-image: 
		-moz-linear-gradient(top,
		   #0a3a86,
		   #4c8de7 50%,
		   #6babf5 95%,
		   #0a3a86),
		-moz-linear-gradient(top,
			#919191,
			#f0f0f0 50%,
			#fff 50%,
			#fff 95%,
			#919191);
	background-repeat: no-repeat, repeat-x;
}
.thumb {
	position:relative;
	-webkit-box-shadow: 2px 2px 3px #666;
	-moz-box-shadow: 2px 2px 3px #666;
	box-shadow: 2px 2px 3px #666;
	height:20px;
	width:20px;
	left: 0px; 
	top: -6px;
	-webkit-border-radius: 10px;
	-moz-border-radius: 10px;
	border-radius: 10px;
	background-image: 
	   -webkit-gradient(linear, left top, left bottom,
		   from(#aaa),
		   color-stop(.5, #ddd),
		   to(#ccc));
	background-image: 
	   -moz-linear-gradient(top,
		   #aaa,
		   #ddd 50%,
		   #ccc);
	cursor: move;
	-webkit-tap-highlight-color: transparent;
}
.thumb:hover, .thumb.hover {
	background-image: 
	   -webkit-gradient(linear, left top, left bottom,
		   from(#6297f2),
		   color-stop(.5, #0251ae),
		   to(#6297f2));
	background-image: 
	   -moz-linear-gradient(top,
		   #6297f2,
		   #0251ae 50%,
		   #6297f2);
}

Notice the slider’s background gradient style. The first background gradient will be the top-most. The last will be the bottom-most. But the top-most is going to be the blue part of the track that appears to the left of the thumb as it is dragged away from the left start of the range slider.

We also need some styles to set the initial states of the three thumbs. Notice that I’ve used background sizing to control the two background gradients. The first is for the blue top-most gradient, the second is for the full width grey gradient.

#redSlider .thumb {
	left: 121px;
}
#redSlider {
	-webkit-background-size: 123px 9px, 100% 9px;
	-moz-background-size: 123px 9px, 100% 9px;
	background-size: 123px 9px, 100% 9px;
}
#greenSlider .thumb {
	left: 156px;
}
#greenSlider {
	-webkit-background-size: 158px 9px, 100% 9px;
	-moz-background-size: 158px 9px, 100% 9px;
	background-size: 158px 9px, 100% 9px;
}
#blueSlider .thumb {
	left: 230px;
}
#blueSlider {
	-webkit-background-size: 232px 9px, 100% 9px;
	-moz-background-size: 232px 9px, 100% 9px;
	background-size: 232px 9px, 100% 9px;
}

So, I’ve defined two gradients with different background repeats: background-repeat: no-repeat, repeat-x; and background sizing with values such as: 123px 9px, 100% 9px. 9px is the height of the slider track. The bottom-most gradient has a width of 100%, and the top-most bluish one gets a width of 123px. By using these values, with very little markup, we can create visually and functionally complex structures.

/**
* Touch enabled support:
*/
/**
*
* Method to set the colors of color swatches and width of the slider progress track when the slider thumb is dragged.
*/
Element.prototype.setupSliderTouch = function( event ) {
	event.preventDefault();
	var el = event.target;
	var touch = event.touches[0];
	curX = touch.pageX - this.parentNode.offsetLeft;
	if (curX <= 0) { 
		curX = 0;
	}
	if (curX > 255) {
		curX = 255;
	}
};
Element.prototype.updateSliderTouch = function( color ) {
	this.style.left =  curX + 'px'; 
	if (color === "red") {
		$("#" + color + "Color").css("background-color: rgb(" + curX +",0,0)");
		$.rgbColor[0] = curX;
	}
	if (color === "green") {
		$("#" + color + "Color").css("background-color: rgb(0," + curX +",0)");
		$.rgbColor[1] = curX;
	}
	if (color === "blue") {
		$("#" + color + "Color").css("background-color: rgb(0,0," + curX +")");
		$.rgbColor[2] = curX;
	}
	
	$("#" + color + "Slider").css("-webkit-background-size:" + (curX + 1) + "px 9px, 100% 9px");
	$("#" + color + "Slider").css("background-size:" + (curX + 1) + "px 9px, 100% 9px");
	
	$("#rgbColor").css("background-color: rgb(" + $.rgbColor[0] + "," + $.rgbColor[1] + "," + $.rgbColor[2] + ")");
	$("#rgbResult").fill($.rgbColor[0] + ", " + $.rgbColor[1] + ", " + $.rgbColor[2]);
	$("#hexResult").fill("#" + $.rgb2hex($.rgbColor[0]) + $.rgb2hex($.rgbColor[1]) + $.rgb2hex($.rgbColor[2]));
};

$("#redSlider > .thumb").bind('touchmove', function(event) {
	this.setupSliderTouch(event);
	this.updateSliderTouch("red");
});
$("#greenSlider > .thumb").bind('touchmove', function(event) {
	this.setupSliderTouch(event);
	this.updateSliderTouch("green");
});
$("#blueSlider > .thumb").bind('touchmove', function(event) {
	this.setupSliderTouch(event);
	this.updateSliderTouch("blue");
});

Basically, I attach a touchmove event to the slider thumbs. The event listener passes the event to the setupSliderTouch method. The first thing the setupSliderTouch method does is to prevent the default interaction from taking place, such as page scrolling. We want the user to be able to move the thumb without scrolling the page. From the event passed in to setupSliderTouch we get the touch event and calculate its x coordinate on the screen. To calculate the touch’s position in relation to the slider, we subtract the left offset of the slider from the pageX of the touch. This gives us the left-most edge of the slider’s thumb. We store this as curX. We check the value of curX. If it is less than zero, we set it back to zero. We do this because this value will be used to set the position of the thumb and one of the RGB values. We don’t want either the thumb being dragged off of the left edge of the slider, nor a value less than zero, since RGB values start at zero. We do the same thing when the curX value is greater than 255 for the same reasons.

The updateSliderTouch method uses the value of the slider’s thumb to calculate and update RGB and Hex values, giving the user visual feedback as the thumb is dragged. Then we use the value of curX to update the background size of the blues background gradient on the slider track:

$("#" + color + "Slider").css("-webkit-background-size:" + (curX + 1) + "px 9px, 100% 9px");
$("#" + color + "Slider").css("background-size:" + (curX + 1) + "px 9px, 100% 9px");

That’s all there is to it. You can try this out online using desktop Safari, Chrome, or Firefox for the mouse version, or on an iPhone, iPod Touch or iPad for the touch version. Or you can download the source code, which I recommend, so you can dig into the CSS and JavaScirpt.

Update: September 15, 2010
If you’re trying this out on an iPhone, I noticed that there seems to be a very slight delay before an initial touch is registered on the screen. This means that in order to slide the thumb, you need to press and hold for a very brief moment before sliding, otherwise no touch gets registered and nothing happens. This doesn’t seem to happen when performing the same action on the iPad. Touches seem more responsive.

iPhone Modal Popup with HTML5, CSS3 & JavaScript

Works on Desktop Safari, Desktop Google Chrome, iPhone, iPod Touch, iPad. Note that I’ve included some styling for Firefox, even though it has no presence to speak of in the mobile space. In particular, Firefox 4 beta still lacks support for CSS3 keyframe animation, although that will make it into a later update.

If you’ve used an iPhone, iPod Touch or iPad, then you’re familiar with the modal popup dialog boxes that the native system uses. Here’s a typical iPhone popup:
Native iPhone modal popup

Notice the white radial gradient behind the popup. I was able to replicate this, but when the user was on a long document and scrolled down to do something that would trigger a popup, I could find no way to center that radial gradient based on the vertical page scroll. I therefore went with a whitesh blur around the popup itself using a CSS3 box shadow. Here’s what my HTML5/CSS3 version looks like:

Originally I thought I would use just one popup per app, re-assigning values to the popup’s part each time the popup was invoked. However I ran into the problem of events from different and I failed to find an elegant way to resolve this. I therefore came up with a scheme where you initialize a popup at the view level, allowing each view to have a custom popup. The initializing script creates the popup and injects it as the last child of the view. The setup script creates the markup for the popup and populates it with values passed as an argument to the initializing script. The setup script also adds basic functionality to the buttons so that clicking either of them will close the popup. The setup script also creates a screen cover which traps events to prevent user interaction with what is behind the popup until it is closed.

The setup script accepts a single argument—an object literal containing key/values pairs to populate the popup. In order for the setup script to create a popup, you must at least pass a value for a valid view in your Web app. This would be like selector: "#Popup". If no other values are passed, the script will produce a basic popup that looks like this:
Basic popup

I used the ChocolateChip mobile JavaScript library to add the interactive functionality to the popup. Here’s the JavaScript that creates the markup and functionality for the popup:

/** 
* 
* A method to initialize a modal popup. By passing a valid selector for a view, this method creates a view based popup with the properties supplied by the options argument. It automatically binds events to both popup buttons to close the popup when the user clicks either. If a callback is passed as part of the opts argument, it gets bound to the "Continue" button automatically.
*
* @method
* 
* ### setupPopup
*
* syntax:
*
*  $.setupPopup({selector: "#News", title: "Subscribe", cancel: });
*
* arguments:
* 
*  - string: string A valid selector for the parent of the tab control. By default the an object literal.
*  - string: string An object literal which can have the following properties:
	title: a string defining the title in the popup.
	message: a string defining the popup message.
	cancelButton: a string defining an alternate name for the cancel button.
	continueButton: a string defining an alternate name for the confirm button.
	callback: a function to run when the user touches the confirm button.
	If no title is supplied, it defaults to "Alert!".
	If no cancelButton value is supplied, it defaults to "Cancel".
	If no continueButton value is supplied, it defaults to "Continue".
* example:
*
*  $.setupPopup({selector: "#buyerOptions"});
*  $.setupPopup({
		selector: "#Popup",
		title: 'Attention Viewers!', 
		message: 'This is a message from the sponsors. Please be seated while we are getting ready. Thank you for your patience.', 
		cancelButton: 'Skip', 
		continueButton: 'Stay for it', 
		callback: function() {
			$('#popupMessageTarget').fill('Thanks for staying with us a bit longer.');
			$('#popupMessageTarget').removeClass("animatePopupMessage");
			$('#popupMessageTarget').addClass("animatePopupMessage");
		}
	});
*
*/
$.setupPopup = function( opts ) {
	if (opts.selector) {
		var selector = opts.selector;
	} else {
		return false;
	}
	var title = "Alert!";
	if (opts.title) {
		var title = opts.title;
	}
	var message = "";
	if (opts.message) {
		var message = opts.message;
	}
	var cancelButton = "Cancel";
	if (opts.cancelButton) {
		cancelButton = opts.cancelButton;
	}
	var continueButton = "Continue";
	if (opts.continueButton) {
		continueButton = opts.continueButton;
	}
	var popup = '<div class="screenCover hidden"></div>';
	popup += '<section class="popup hidden"><div>';
	popup += '<header><h1>' + title + '</h1></header>';
	popup += '<p>' + message +'</p><footer>';
	popup += '<div class="button cancel">' + cancelButton + '</div>';
	popup += '<div class="button continue">' + continueButton + '</div></footer></div></section>';
	$(selector).insertAdjacentHTML("beforeEnd", popup);
	// Bind event to close popup when either button is clicked.
	$$(selector + " .button").forEach(function(button) {
		button.bind("click", function() {
			$(selector + " .screenCover").addClass("hidden");
			$(selector + " .popup").addClass("hidden");
		});
	});
	
	if (opts.callback) {
		var callbackSelector = selector + " .popup .continue";
		$(callbackSelector).bind("click", function() {
			opts.callback();
		});
	}
	
};

And here is an initialization of a popup:

$.setupPopup(
	{
		selector: "#Popup",
		title: 'Attention Viewers!', 
		message: 'This is a message from the sponsors. Please be seated while we are getting ready. Thank you for your patience.', 
		cancelButton: 'Skip', 
		continueButton: 'Stay for it', 
		callback: function() {
			$('#popupMessageTarget').fill('Thanks for staying with us a bit longer.');
                        // Remove this class in case the popup was opened previously.
			$('#popupMessageTarget').removeClass("animatePopupMessage");
                        // Then add the class to trigger an animation of the message being displayed.
			$('#popupMessageTarget').addClass("animatePopupMessage");
		}
	}
);

Now that a popup has been created and populated with the desired values, we need a way to show it. Before actually showing the popup, the $.showPopup method display a screen cover which captures user interaction and thereby prevents the interface behind the popup from being accessed until the popup is dispelled. The showPopup method accepts one argument, a selector indicating a uniquely identifiable node that contains the popup as a descendant.

$.showPopup = function( selector ) {
	var screenCover = $(selector + " .screenCover");
        // Make the screen cover extend the entire width of the document, even if it extends beyond the viewport.
	screenCover.css("height:" + (window.innerHeight + window.pageYOffset) + "px");
	var popup = $(selector + " .popup");
	$(selector + " .popup").style.top = ((window.innerHeight /2) + window.pageYOffset) - (popup.clientHeight /2) + "px";
	$(selector + " .popup").style.left = (window.innerWidth / 2) - (popup.clientWidth / 2) + "px";
	$(selector + " .screenCover").removeClass("hidden");
	$(selector + " .popup").removeClass("hidden");
};

With this method defined we can now show the popup as need. Here’s a script that attaches an event handler to a button with a class of “openPopup” for a popup somewhere among the descendant nodes of a node with an id of “Tabs”:

$("#Tabs .openPopup").bind("click", function() {
	$.showPopup("#Tabs");
});

OK, so we have the markup and functionality for the popup, but we don’t have the look. We’ll take care of that next. In order to create the unique look of the iPhone popup, I use several layers for encasing borders and composited transparent background gradients. Originally I had two gradients, the dark blue linear gradient and the whitish radial gradient, layered on top of each other as multiple backgrounds. But Google Chrome had a problem rendering the underlying linear gradient, ignoring its transparent alpha values and rending the colors as opaque. I was therefore forced to break them out into separate elements. The end result is the same. When the popup is created by the setup script, it is given a class of “hidden.” This defines its scale as 0% and its opacity as 0%. When we execute the showPopup method, it removes that “hidden” class. Because the popup has basic transitions properties defined on it, its scale and opacity transition from zero to full, making it appear to popup out of no where. The scripts also always make sure that the popup is centered in the viewport, regardless of where it was displayed when scrolling down a long document.

For their modal popups, Apple always indicates the default button, what would be equivalent to a submit or OK button, with slightly lighter colors so that it stands out from the other button, which is the equivalent of a cancel/close button. I have the buttons located in a footer and I use CSS3’s flexible box model styles to make the buttons position and size them selves according to available space.

/* Modal Popup Styles */
section.popup {
	width: 75%;
	max-width: 300px;
	border: solid 1px #72767b;
	-webkit-box-shadow: 0px 4px 6px #666, 0 0 50px rgba(255,255,255,1);
	-moz-box-shadow: 0px 0px 1px #72767b,  0px 4px 6px #666;
	box-shadow: 0px 0px 1px #72767b, 0px 4px 6px #666;
	-webkit-border-radius: 10px;
	-moz-border-radius: 10px;
	border-radius: 10px;
	padding: 0px;
	opacity: 1;
	-webkit-transform: scale(1);
	-webkit-transition: all 0.25s  ease-in-out;
	position: absolute;
	z-index: 1001;
	margin-left: auto;
	margin-right: auto;
	background-image: 
		-webkit-gradient(linear, left top, left bottom,
			from(rgba(0,15,70,0.5)),
			to(rgba(0,0,70,0.5)));
}
section.popup.hidden {
	opacity: 0;
	-webkit-transform: scale(0);
	top: 50%;
	left: 50%;
	margin: 0px auto;
}
section.popup > div {
	border: solid 2px #e6e7ed;
	-webkit-border-radius: 10px;
	-moz-border-radius: 10px;
	border-radius: 10px;
	padding: 10px;
	background-image: 
	   -webkit-gradient(radial, 50% -1180, 150, 50% -280, 1400,
		   color-stop(0, rgba(143,150,171, 1)),
		   color-stop(0.48, rgba(143,150,171, 1)),
		   color-stop(0.499, rgba(75,88,120, .9)),
		   color-stop(0.5, rgba(75,88,120,0)));
	color: #fff;
	text-shadow: 0px -1px 1px #000;
}
section.popup header {
	background: none;
	-webkit-border-top-left-radius: 10px;
	-webkit-border-top-right-radius: 10px;
	-moz-border-radius-topleft: 10px;
	-moz-border-radius-topright: 10px;
	border-top-left-radius: 10px;
	border-top-right-radius: 10px;
	border: none;
	color: #fff;
	text-shadow: 0px -2px 1px #000;
}
section.popup header > h1 {
	letter-spacing: 1px;
}
section.popup footer
{
	display: -webkit-box;
	-webkit-box-orient: horizontal;
	-webkit-box-pack:justify;
	-webkit-box-sizing: border-box;
	display: -moz-box;
	-moz-box-orient: horizontal;
	-moz-box-pack:justify;
	-moz-box-sizing: border-box;
}
section.popup footer > .button {
	-webkit-box-flex: 2;
	-moz-box-flex: 1;
	display: block;
	text-align: center;
	-webkit-box-shadow: none;
	-moz-box-shadow: none;
	box-shadow: none;
	margin: 10px 5px;
	height: 32px;
	font-size: 18px;
	line-height: 32px;
	-webkit-border-radius: 8px;
}
section.popup footer > .button.cancel {
	background-image: 
		-webkit-gradient(linear, left top, left bottom, 
			from(#828ba3), 
			color-stop(0.5, #4c5a7c), 
			color-stop(0.5, #27375f), 
			to(#2e3d64));
}
section.popup footer > .button.continue {
	background-image: 
		-webkit-gradient(linear, left top, left bottom, 
			from(#b0b6c4), 
			color-stop(0.5, #7a839b), 
			color-stop(0.5, #515d7c), 
			to(#636e8a));
}
section.popup footer > .button:hover, .popup footer > .button.hover {
	background-image: 
		-webkit-gradient(linear, left top, left bottom, 
			from(#70747f), 
			color-stop(0.5, #424857), 
			color-stop(0.5, #171e30), 
			to(#222839));
}
.screenCover {
	width: 100%;
	height: 100%;
	display: block;
	background-color: rgba(0,0,0,0.5);
	position: absolute;
	z-index: 1000;
	top: 0px;
	left: 0px;
}
.screenCover.hidden {
	display: none;
}

You can try this out online or download the source code to play around with it.

iPhone Style Radios Buttons with HTML, CSS & JavaScript


Works on desktop Safari, desktop Google Chrome, Android, iPhone, iPod Touch and iPad.

Have you ever surfed to a Web page on the iPhone or iPod Touch’s Safari browser and come across a form with standard radio buttons? It’s a pretty miserable experience trying to hit them with your finger. You have to zoom in to do so, maybe zoom in a lot. When Apple was designing the interface for the iPhone, they put a lot of thought into how to make conventional interface elements easier to use in a touch environment. If you think about it, what is a group of radio buttons but a list of items to select from. And only one item can be selected at a time. To cover this requirement Apple came up with the radio table control. A radio table is just a list of items, same as a radio button group. Only one list item can be chosen, and this is indicated by a checkmark on that particular list item which correlates to the single radio button being selected out of a group.

The radio button list looks like this:
Radio Button List

One of the things that I really can’t understand is why people think a mobile touch interface needs radio buttons like on the desktop browser. All the other mobile frameworks are providing ways to implement the standard tiny, round radio buttons. They don’t work for touch interfaces. Get over it. The radio list works better for touch. Embrace it and love it and it will love you. Wait, I didn’t really mean that, but you get the picture. I have a hard enough time hitting normal sized controls designed for the iPhone. Heck, sometimes I can’t even find my iPhone, but that’s another issue.

To make this more like the Web equivalent of radio buttons I added real radio buttons to my solution. Here’s the markup to implement them (note that you still need to great the grouping of the radio buttons by giving each radio button in the list the same name):

<ul id="activityChoices" class="radioList">	
	<li>
		<span>Go eat something</span> 
		<span class="check">&#x2713</span>
		<input type="radio" name="activity" value="Go eat something" />
	</li>
	<li>
		<span>Take a nap</span> 
		<span class="check">&#x2713</span>
		<input type="radio" name="activity" value="Take a nap" />
	</li>
	<li>
		<span>Get some work done</span> 
		<span class="check">&#x2713</span>
		<input type="radio" name="activity" value="Get some work done" />
	</li>
	<li>
		<span>Play a game</span> 
		<span class="check">&#x2713</span>
		<input type="radio" name="activity" value="Play a game" />
	</li>
</ul>

Notice that the last item in each list item is the radio input. Please leave this as such, since it makes it easy for us to target the actual radio button as the last child of the list items child nodes. If you have a need to add other things into the list, insert them elsewhere in the list items collection of child nodes.

We’ll use CSS to hide the radio buttons and when a user touches a list item, we’ll use JavaScript to set the checked state of that list item’s radio button to true. After that, what you do with the user interaction is up to you. In many cases that initial choice can immediately trigger a corresponding action, or you may wait until the user takes a decisive final action that triggers a submit or post of all the selected inputs. Notice the span with the class “check.” It contains a hex value of “&#x2713” which is an HTML entity for a standard check mark. We’ll use CSS to position and hide or show it depending on the user’s interaction.

Here’s the CSS needed to make our list look like the iPhone one. Since the radio button group is based on the list control type, it shares some styles with standard lists:

.list, .radioList {
	-webkit-box-shadow: 2px 2px 4px #666;
	-webkit-border-radius: 12px;
	-moz-box-shadow: 2px 2px 4px #666;
	-moz-border-radius: 12px;
	box-shadow: 2px 2px 4px #666;
	border-radius: 12px;
}
.list li, .radioList li {
	cursor: pointer;
	padding: 8px;
	border-left:  1px solid #acacac;
	border-right: 1px solid #acacac;
	border-bottom: 1px solid #acacac;
	background-color: #fff;
	font-weight: bold;
	-webkit-tap-highlight-color: transparent;
}
.list li:hover, .radioList li:hover {
	background-image: 
		-webkit-gradient(linear, left top, left bottom, 
			from(#4286f5), 
			to(#194fdb));
	background-image: 
		-moz-linear-gradient(top, 
			#4286f5, 
			#194fdb);
	color: #fff;
}
.list li:hover:after, .radioList li:hover:after {
	color: #fff;
}
.list li:first-of-type, .radioList li:first-of-type {
	border-top: 1px solid #acacac;
	-webkit-border-top-right-radius: 10px;
	-webkit-border-top-left-radius: 10px;
	-moz-border-radius-topright: 10px;
	-moz-border-radius-topleft: 10px;
	border-top-right-radius: 10px;
	border-top-left-radius: 10px;
}
/** 
	Styles for single choice lists.
	These are the same in functionality as a 
	radio button group.
*/
.radioList li > .check {
	float: right;
	-webkit-transition: all 0.125s  ease-in-out;
	-moz-transition: all 0.125s  ease-in-out;
	transition: all 0.125s  ease-in-out;
	opacity: 0;
}
.radioList li.selected > .check {
	opacity: 1;
	color: #496691;
}
.radioList li > .check, .radioList li.selected:hover > .check {
	color: #fff;
}
.radioList li > input[type="radio"] {
	display: none;
}

The selector radioList li > .check defines the check mark. We set it’s initial opacity to 0 so that it is completely transparent. When the user selects a list item by clicking/touching, we add a “selected” class to the list item. The selector .radioList li.selected > .check then sets the check mark’s opacity to 100%.

To make all the behavior work, we need to write some JavaScript for a reusable control. We’ll use the light, mobile JavaScript framework ChococlateChip.

/** 
* 
* A method to initialize a list of radios buttons to present the user with a group of single choice options. It takes as the main argument, a unique selector identifying the view or section where the radio list resides.
*
* @method
* 
* ### RadioButtons
*
* syntax:
*
*  $.RadioButtons(selector);
*
* arguments:
* 
*  - string: string A valid selector for the parent of the tab control. By default the selector will target a class, id or tag of the radio list itself, so if you want to pass in a selector for a parent tag, such as an article, section or div tag, you'll need to make sure to put a trailing space on the end of the selector string.
*  - function: function A valid function as a callback. This is optional. The callback gets passed a reference to the clicked item, so you can access it in your callback function.
* 
* example:
*
*  $.RadioButtons("#buyerOptions");
*  $.RadioButtons("#buyerOptions", function(choice) {
	   // Output the value of the radio button that was selected.
	   // Since the actual radio button is the last item in a radio
	   // button list, we can use the last() method to get its value.
	   console.log(choice.last().value);
   };
*
*/
$.RadioButtons = function( viewSelector, callback ) {
	var items = viewSelector + ".radioList li";
	var radioButtons = $$(items);
	radioButtons.forEach(function(item) {
		item.bind("click", function() {
			radioButtons.forEach(function(check) {
				check.removeClass("selected");
			});
			this.addClass("selected");
			this.last().checked = true; 
			if (callback) {
				callback(item);
			}
		});
	});
};	

Because the radio input is the last child of the list’s node collection, we can set its checked value to true when the user clicks or touches a list item. We do this with the line: this.last().checked = true; We also manage toggling of the selected state of a list item by adding and removing a “selected” class. This hides or shows the check mark. We also have a conditional block to check for a callback. If one was passed as an argument, we invoke it. We pass in a reference to the list item that was clicked using the term “item.” This allows us to reference the clicked item in our callback. We can initialize a radio button list as follows:

// Radio button initialization:
$.RadioButtons("#activityChoices", function(item){
	$("#RadioButtons .response").fill(item.last().value);
});

In the above code we’re passing in a reference to the clicked list item in an anonymous function which fills a span with a class of “response” with the value of the list item’s radio button.

The radio button list has an id of “#activityChoices,” so I just pass that in. If “#activityChoices” were a parent node, I would have had to written the selector thus (notice the trailing space at the end before the closing parenthesis): $.RadioButtons(“#activityChoices “); This differentiation is necessary because the selector passed in gets concatenated with “.radioList li” to set up the radio button list’s functionality. There is no way for the control to know when you are targeting the list itself or a parent node. If the selector is the list itself, “.radioList li” gets appended to that, but if the selector is a parent node, you need to indicate that with a trailing space so that the “.radioList li” gets appended with the space separating. Otherwise the resulting complete selector will not identity the radio button list properly and nothing will get initialized. I hope this is clear. Yeah, I could have written the control to check to see if the selector was the list or a parent node, but that would have resulted in a performance hit as the code would have had to do quite a bit of evaluation to determine what the selector relation was.

Remember that the callback is optional. That means if you are construction a form with a submit process, then all you need to do for the radio button list is pass in a correct selector to initialize its behavior. You’ll then get the user’s choice during the submit process.

You can try out an example online or download the source code.