ChocolateChip-UI for jQuery

ChocolateChip-UI has been ported to jQuery. This means if your preferred JavaScript library is jQuery, you can now use this version of ChocolateChip-UI for creating mobile apps. It uses the latest version of jQuery for DOM traversing, manipulation and Ajax calls. It also includes jquery.tmpl.js to accommodate your tempting needs.

Because ChocolateChip.js was designed to work similar to jQuery, in most cases the port was trivial. However, jQuery’s wrapping of nodes in its object instead of returning an actual node introduced complications that I did run into in the regular version of ChocolateChip.

The end result of the port is that ChocolateChip-UI’s controls work the same as they always have. There are only some slight difference in how callbacks are handled in a couple of places. If you’ve already been using the regular version of ChocolateChip and want to switch to the jQuery version, open up and examine the provided examples to see if you need to change anything. In most cases you won’t.

ChocolateChip-UI for jQuery:
On Github: rbiggs/chocolatechip-ui-jq

To learn more about how to use ChocolateChip-UI, visit ChocolateChip-UI.com.

ChocolateChip-UI 1.0

For those of you who visit my blog looking for how to put together different widgets with HTML and CSS, I’m proud to announce the launch of ChocolateChip-UI 1.0. This is a major update with many refinements, bug fixes and new features, such as titled lists, alphabetical lists, and iPad style popovers. If you like the examples in these blog post and would like to use them, you can download an entire framework with everything in this blog and more, all ready to use. And, if you’re good with CSS, it’s fairly easy to customize the look and feel of the framework.

Visit ChocolateChip-UI.com.

Here’s a list of the types of widgets, controls and layout options that ChocolateChip-UI offers:

  • Toolbars
  • Navbars
  • Buttons
  • Icons
  • Navigation Lists
  • Table Views
  • Selection Lists
  • Switch Controls
  • Popups
  • Popovers
  • Expanders
  • Progress Bars
  • Activity Indicators
  • Actionsheets
  • Tab Bars
  • Segmented Controls
  • Deletion Lists
  • Sliders
  • Carouses
  • Scroll Panels
  • Paging Controls
  • Split Layout

Here’s what some of those layouts and controls look like:

This slideshow requires JavaScript.

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.

Practical Examples of the Flexible Box Model

If there’s one thing in CSS3 that really gives me warm fuzzies, it’s the flexible box model. What it does is provides a way to create many layout affects that otherwise would require workarounds with float or positioning or both. And there are many types of layouts that without out it would require JavaScript to create the same effect. Sadly, at present the flexible box model is only implemented in Firefox, Safari and Chrome. As it turns out, Microsoft’s IE team approached the W3C standards teams with a proposal for a grid-based layout module. It appears to be based on experience implementing the Silverlight grid layout system, which is a good thing. Silverlight grids are a powerful layout tool and is the most important feature for creating interfaces with Silverlight. Because this grid proposal is very solid, the W3C has dropped all further work on the flexible box model and instead are moving ahead in finalizing the draft for the grid layout module. If you read that speck, you’ll realize how much we need a CSS grid system. For now, however, we do have the flexible box model working in Firefox, Chrome and Safari, as well as on mobile Webkit, which includes iOS, Android, WebOS, and Blackberry. This means that if you’re doing mobile development you can use the flexible box model today to help you implement your layout needs. Once you start using the flexible box model, you’ll hate having to go back to situations where it’s not available.

The flexible box model got a lot of attention from a post by Alex Russell back in August 2009. The good thing is that in his post he showed some of the practical things that the flexible box model addresses and provided a stylesheet with a small subset of the flexible box model properties that people could use right away. His post has been replicated and linked to all over the Web. Unfortunately a lot of people who are not familiar with the spec for the flexible box model are under the impression that what’s in his stylesheet is it. So, with that in mind I’m loosing another stylesheet on the public that allows a greater utilization of the flexible box model. I’ll also give you a layout where a lot of these are in use so that you can see how they work.

Before I get going let me say this. The flexible box model is not perfect. It isn’t supported by IE9 or Opera. And now it looks like the W3C is bypassing it for a more robust grid system. Personally, I’d like to see something like the Silverlight grid system combined with aspects of the flexible box model. That would be the best of both approaches. If you’re targeting the mobile Web, in other words you intend on target Webkit browsers, you can expect robust support for the flexible box model. I doubt it’s going to go away just because the W3C doesn’t include it in any recommendation. I expect it to remain in Webkit for the foreseeable future because it’s already been in use for a number of years.

The flexible box model is about the way a collection of child nodes gets laid out in relation to each other and their parent node. To achieve its layout goals, the flexible box model offers properties for the parent node as well as for the child nodes that determine the layout characteristics of the child nodes.

To work with the flexible box model you need to define its display property to box:

#myDiv {
    display: -webkit-box;
    display: -moz-box;
}

Elements with display set to box can order their child nodes in two orientations: vertical or horizontal. If no orientation is provided, the box defaults to vertical:

#myDiv {
    display: -webkit-box;
   -webkit-box-orient: horizontal;
    display: -moz-box;
    -moz-box-orient: horizontal;
}

Besides defining the orientation, you can also designate what direction the child elements stack, either normal or reverse. A box direction of reverse means the elements display in the opposite order in which they physically appear in the document, so that the first would be last and the last first. By default the box direction is normal stacking order.

Then there is the packing order. This allows you to define how the child elements are packed inside the parent. By default they are packed in from the beginning of the parent. For vertical orientation this is the top and for horizontal orientation this is the left. Other packing orders are end, center and justify. If the packing order is end, for a vertical orientation the elements will stack up from the bottom. For a box with horizontal alignment, the boxes will stack from the right. A packing order of center means that for vertical orientation the child elements will be centered vertical with any left over space displayed equally at the top and bottom. For horizontal orientation a packing order of center means the elements are centered horizontally with left over space equally divided on the left and right. A packing order of justified means that any available space is spread equally between the child elements, for vertical orientation this is vertical spacing, and for horizontal orientation this is horizontal spacing.

Box-align-start

A box with alignment set to "start"

box-align-end

A box with alignment set to "end"

box-align-center

A box with alignment set to "center"

And elements can have their box alignment defined. The default is stretch. This stretches the dimensions of the child elements to fill the parent box. If the alignment is start, for horizontal orientation the elements are aligned to the top of the parent. If the orientation is vertical, they are aligned to the left of the parent. An alignment of end will align elements with horizontal alignment to the bottom of the parent. With vertical orientation they will be aligned to the right of the parent. An alignment of center will align horizontal elements along the horizontal center of the parent and for vertical orientation it will center them along the vertical center of the parent. There is also an alignment of baseline, but this is only for horizontal orientation. It aligns the elements along their horizontal baseline.

Then there is a set of properties that you can define on the child elements. These are flex and ordinal group. The flex property tells the browser how to deal with the dimensions of the child element. If you have three child elements and they don’t fill their parent, giving one of the a value of flex:1 will cause that element to take up all the left over space. If you gave one element flex: 1 and another one flex: 2, the available space would be divided up such that the element with flex: 1 would get one third of the available space and the element with flex: 2 would get two thirds of the available space. Of course the element with no flex value would default to whatever its width is. The ordinal group property allows you to designate groups of elements so that they appear in a different order than their document order. I’m not so sure about the practical use for this property. I’ve thought about it for months and have not been able to come up with a use case where I would need it. But it’s there.

I’ve created a flexible box model stylesheet with classes for all the various box properties. This means you can add the classes to an element to build out the definition you need for an element. I’ve also put together a interactive test case where you can dynamically toggle a number of the box properties and see their effect in real time. You can try it out online if you’re using Firefox, Chrome or Safari, or you can download the working example to dissect and learn.

Multiple Background Images & Animation

Multiple background images allow one to build up complex layered visual effects using one element. In the past such effects would require each background image rendered inside its own element, these being either nested or stacked on top of each other with positioning. When I was working on creating the progress bar example, I ran to a problem where I couldn’t seem to get a specific layer to animate. I could figure out what was going on. Recently, after looking at the code and fiddling with it, I found out what the problem was. Animation of background images works a little differently from other CSS properties. Because multiple backgrounds consists of multiple definitions, it works more like other properties with multiple property values: margins, borders, padding. For example, you can animate all borders on an element, otherwise you can animate a single border. Unfortunately, with multiple backgrounds there is no easy way to single out an individual background image for animation as you can with a border, margin or padding property.

Now the thing to bare in mind when dealing with multiple background images is the stacking order. The first image defined is the topmost image, and the last image defined is the bottommost. Same thing with animations for multiple background images. So, in the case of the animated progress bar, I wanted to animate the bottommost gradient image which consisted of white slanted bars. The rest of the progress bar was fine stable. Well, except that I used a single animation which would instead affect the topmost layer, making it impossible for me to get the stacking layer they way I wanted. Here is the gradient:

background-color: rgb(56,138,213);
background-image:
	-webkit-gradient(linear, 18 0, 0 10,
		color-stop(0.23, rgba(255,255,255,0)),
		color-stop(0.3, rgba(255,255,255,0.8)),
		color-stop(0.3, rgba(255,255,255,1)),
		color-stop(0.7, rgba(255,255,255,1)),
		color-stop(0.7, rgba(255,255,255,0.8)),
		color-stop(0.77, rgba(255,255,255,0))),
	-webkit-gradient(linear, 0 0, 0 100%,
		color-stop(0, rgba(255,255,255,.8)),
		color-stop(0.45, rgba(255,255,255,.05)),
		color-stop(0.55, rgba(0,0,0,.05)),
		color-stop(0.85, rgba(0,0,0,.2)),
		color-stop(0.98, rgba(0,0,0,.5))),
	-webkit-gradient(linear, 0 0, 0 100%,
		color-stop(0.20, transparent),
		color-stop(0.20, rgba(255,255,255,.5)),
		color-stop(0.32, rgba(255,255,255,.5)),
		color-stop(0.32, transparent));

To animate this, I was using a key-frame animation that moved the x axis of the background gradient across the element from 0 to 100% in a loop:

@-webkit-keyframes progressBarAnim {
	0% { background-position-x:  0%; }
	100% { background-position-x: 100%; }
}

If you ran my previous example of the progress bar, it animates as you would expect, except one problem. The topmost gradient layer is the part that should be on the bottom. Yet every time I positioned it to where I wanted it, it wouldn’t animate. In my mind I was thinking that the key frame animation defined above would be animating all the background images. Actually, it doesn’t. It only animates the topmost image background, which is why I had to have the part I wanted to animate on top. Unfortunately I didn’t figure this out until recently. After a lot of fiddling and digging into what was going on with animation of multiple background images, I finally sorted it all out. When defining animations you have to start from the top and work you way down. You don’t have to include an animation for every background image, only down to the layer you need to. But you do have to include all the layers above the animated one up to the topmost one. So here’s my new stacking order for the CSS the way I actually wanted it:

background-color: rgb(56,138,213);
background-image:
	-webkit-gradient(linear, 0 0, 0 100%,
		color-stop(0, rgba(255,255,255,.8)),
		color-stop(0.45, rgba(255,255,255,.05)),
		color-stop(0.55, rgba(0,0,0,.05)),
		color-stop(0.85, rgba(0,0,0,.2)),
		color-stop(0.98, rgba(0,0,0,.5))),
	-webkit-gradient(linear, 0 0, 0 100%,
		color-stop(0.20, transparent),
		color-stop(0.20, rgba(255,255,255,.5)),
		color-stop(0.32, rgba(255,255,255,.5)),
		color-stop(0.32, transparent)),
	-webkit-gradient(linear, 18 0, 0 10,
		color-stop(0.23, rgba(255,255,255,0)),
		color-stop(0.3, rgba(255,255,255,0.8)),
		color-stop(0.3, rgba(255,255,255,1)),
		color-stop(0.7, rgba(255,255,255,1)),
		color-stop(0.7, rgba(255,255,255,0.8)),
		color-stop(0.77, rgba(255,255,255,0)));

And here’s the key frame animation, notice the extra animations for the upper layers:

@-webkit-keyframes progressBarAnim {
	0% { background-position-x:  0%, 0%, 0%; }
	100% { background-position-x: 0%, 0%, 100%; }
}

So remember, in the above key frame animation the first value if for the topmost layer and the last value is for the bottom most layer.

To show the difference in the stacking order, I changed the white stripe that goes horizontally across the progress bar to black. In the wrong stacking order version you can see that its actually behind the white stripes. The corrected version with multiple background animations has it correctly on top:

progress bar with incorrect stacking order

progress bar with incorrect stacking order



progress bar with correct stacking order

progress bar with correct stacking order

Of course, the final product would not be a black streak, it would be white. This was just to show how the stacking order was previously wrong.

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.

ChocolateChip Has Its Own Blog

ChocolateChip, the little guy that does big things

So, ChocolateChip, the tiny JavaScript mobile Web framework that is only 8k when minified, now has its own blog: ChocolateChip-Mobile.net. I put this blog together to show how ChocolateChip works and how you can use it to accomplish your coding needs. I also talk about best coding practices with ChocolateChip.

ChocolateChip can be so small because it doesn’t have to support ancient browsers or compensate for cross-browser nightmares. Instead it takes advantage of modern browsers’ implementation of the features in ECMAScript 5 and DOM level 3. The idea was to keep ChocolateChip simple, avoiding object wrappers and object obfuscation, and making everything interchangeable with regular JavaScript. That means you can adjust ChocolateChip to your coding style, not the other way around. You can substitute any ChocolateChip for your own code at any time. As a matter of fact, if you don’t like the default $, $$ aliases that ChocolateChip uses, open up the files and change them to whatever you want. ChocolateChip is open source with a BSD license, so if you want to add some feature, feel free to. And if you feel like sharing your feature with the rest of us, feel free to contact me.

Have a great day and enjoy your ChocolateChip.