Tuesday, February 14, 2012

Create an Image Rotator with Description (CSS/jQuery)


Create an Image Rotator with Description (CSS/jQuery)

By Soh Tanaka | Published May 4th, 2009 in Tutorials
An image rotator is one great way to display portfolio pieces, eCommerce product images, or even as an image gallery. Although there are many great plugins already, this tutorial will help you understand how the image rotator works and helps you create your own from scratch.

Creating an Image Rotator

View Demo of Image Rotator
Image Rotator - CSS jQuery

Step1. HTML – Image Rotator Wireframe

Start by building the html wireframe of the layout. As you can see in the image below, there will be two major sections (the main image section and the thumbnail list section). In addition to the sections for images, the third section, labeled “desc”, will contain the main_image description.
Image Rotator - CSS jQuery
main_image Section HTML
Close Me!

Title

Date
Copy

image_thumb Section HTML
Note – The thumbnail list section will be very similar in markup as the main image section, but each will all be encapsulated in its own list item.

  • Image Name

    Title

    Date
    Copy


Step 2. CSS – Image Rotator Wireframe

Next, it’s time to style the image rotator’s HTML wireframe with CSS.
main_image section CSS
.main_image {
width: 598px;
height: 456px;
float: left;
background: #333;
position: relative;
overflow: hidden; /*--Overflow hidden allows the description to toggle/tuck away as it slides down--*/
color: #fff;
}
.main_image h2 {
font-size: 2em;
font-weight: normal;
margin: 0 0 5px;
padding: 10px;
}
.main_image p {
font-size: 1.2em;
line-height: 1.6em;
padding: 10px;
margin: 0;
}
.block small { /*--We'll be using this same style on our thumbnail list--*/
font-size: 1em;
padding: 0 0 0 20px;
background: url(icon_calendar.gif) no-repeat 0 center;
}
.main_image .block small {margin-left: 10px;}
.main_image .desc{
position: absolute;
bottom: 0;
left: 0; /*--Stick the desc class to the bottom of our main image container--*/
width: 100%;
display: none; /*--Hide description by default, if js is enabled, we will show this--*/
}
.main_image .block{
width: 100%;
background: #111;
border-top: 1px solid #000;
}
.main_image a.collapse { /*--This is our hide/show tab--*/
background: url(btn_collapse.gif) no-repeat left top;
height: 27px;
width: 93px;
text-indent: -99999px;
position: absolute;
top: -27px;
right: 20px;
}
.main_image a.show {background-position: left bottom;}

image_thumb section CSS
.image_thumb {
float: left;
width: 299px;
background: #f0f0f0;
border-right: 1px solid #fff;
border-top: 1px solid #ccc;
}
.image_thumb img {
border: 1px solid #ccc;
padding: 5px;
background: #fff;
float: left;
}
.image_thumb ul {
margin: 0;
padding: 0;
list-style: none;
}
.image_thumb ul li{
margin: 0;
padding: 12px 10px;
background: #f0f0f0 url(nav_a.gif) repeat-x;
width: 279px;
float: left;
border-bottom: 1px solid #ccc;
border-top: 1px solid #fff;
border-right: 1px solid #ccc;
}
.image_thumb ul li.hover { /*--Hover State--*/
background: #ddd;
cursor: pointer;
}
.image_thumb ul li.active { /*--Active State--*/
background: #fff;
cursor: default;
}
html .image_thumb ul li h2 {
font-size: 1.5em;
margin: 5px 0;
padding: 0;
}
.image_thumb ul li .block {
float: left;
margin-left: 10px;
padding: 0;
width: 170px;
}
.image_thumb ul li p{display: none;}/*--Hide the description on the list items--*/

Step3. jQuery – Image Rotation Effect

If you are new to jQuery or have not had much experience with it, first go over the basics.
Show Image Description and Set Transparency on Block
To degrade gracefully, the image banner description is set to be hidden at default with CSS (refer to the “.main_image .desc” class in the CSS). We will show the image description if JavaScript is enabled.

$(".main_image .desc").show(); //Show Banner
$(".main_image .block").animate({ opacity: 0.85 }, 1 ); //Set Opacity

Click and Hover Events for Image List
The following script will change the main_image when a list-item in the image_thumb is clicked. Each line also contains a comment explaining which jQuery actions are being performed.
$(".image_thumb ul li:first").addClass('active'); //Add the active class (highlights the very first list item by default)
$(".image_thumb ul li").click(function(){
//Set Variables
var imgAlt = $(this).find('img').attr("alt"); //Get Alt Tag of Image
var imgTitle = $(this).find('a').attr("href"); //Get Main Image URL
var imgDesc = $(this).find('.block').html(); //Get HTML of the "block" container
var imgDescHeight = $(".main_image").find('.block').height(); //Find the height of the "block"

if ($(this).is(".active")) { //If the list item is active/selected, then...
return false; // Don't click through - Prevents repetitive animations on active/selected list-item
} else { //If not active then...
//Animate the Description
$(".main_image .block").animate({ opacity: 0, marginBottom: -imgDescHeight }, 250 , function() { //Pull the block down (negative bottom margin of its own height)
$(".main_image .block").html(imgDesc).animate({ opacity: 0.85, marginBottom: "0" }, 250 ); //swap the html of the block, then pull the block container back up and set opacity
$(".main_image img").attr({ src: imgTitle , alt: imgAlt}); //Switch the main image (URL + alt tag)
});
}
//Show active list-item
$(".image_thumb ul li").removeClass('active'); //Remove class of 'active' on all list-items
$(this).addClass('active'); //Add class of 'active' on the selected list
return false;
}) .hover(function(){ //Hover effects on list-item
$(this).addClass('hover'); //Add class "hover" on hover
}, function() {
$(this).removeClass('hover'); //Remove class "hover" on hover out
});

Toggle the Hide/Show Option
This is fairly simple. On each click, either show or hide the description.

$("a.collapse").click(function(){
$(".main_banner .block").slideToggle(); //Toggle the description (slide up and down)
$("a.collapse").toggleClass("show"); //Toggle the class name of "show" (the hide/show tab)
});

View Demo of Image Rotator
Image Rotator - CSS jQuery

Conclusion

Do keep in mind these jQuery driven image rotators do not degrade in the best fashion. As you can see, when you disable JavaScript, each thumbnail must be clicked on to get the larger image (which opens in the same window). But for those who have a user base with JavaScript enabled, you are in the clear and it can be used and customized to fit various scenarios.
Experiment and customize this to fit your needs. If you have any questions, concerns, suggestions, or comments, please do not hesitate to let me know.
Awesome cloud hosting for designers and their files and apps.
Credits: Much appreciation to Glenn Jones for allowing me to use his beautiful illustrations for the example images.

Sunday, February 12, 2012

An Introduction to CSS 3-D Transforms

Ladies and gentlemen, it is the second decade of the third millennium and we are still kicking around the same 2-D interface we got three decades ago. Sure, Apple debuted a few apps for OSX 10.7 that have a couple more 3-D flourishes, and Microsoft has had that Flip 3D for a while. But c’mon – 2011 is right around the corner. That’s Twenty Eleven, folks. Where is our 3-D virtual reality? By now, we should be zipping around the Metaverse on super-sonic motorbikes.
Granted, the capability of rendering complex 3-D environments has been present for years. On the web, there are already several solutions: Flash; three.js in <canvas>; and, eventually, WebGL. Finally, we meagre front-end developers have our own three-dimensional jewel: CSS 3-D transforms!

Rationale

Like a beautiful jewel, 3-D transforms can be dazzling, a true spectacle to behold. But before we start tacking 3-D diamonds and rubies to our compositions like Liberace‘s tailor, we owe it to our users to ask how they can benefit from this awesome feature.
An entire application should not take advantage of 3-D transforms. CSS was built to style documents, not generate explorable environments. I fail to find a benefit to completing a web form that can be accessed by swivelling my viewport to the Sign-Up Room (although there have been proposals to make the web just that). Nevertheless, there are plenty of opportunities to use 3-D transforms in between interactions with the interface, via transitions.
Take, for instance, the Weather App on the iPhone. The application uses two views: a details view; and an options view. Switching between these two views is done with a 3-D flip transition. This informs the user that the interface has two – and only two – views, as they can exist only on either side of the same plane.
iPhone Weather App 3D flip transition Flipping from details view to options view via a 3-D transition
Also, consider slide shows. When you’re looking at the last slide, what cues tip you off that advancing will restart the cycle at the first slide? A better paradigm might be achieved with a 3-D transform, placing the slides side-by-side in a circle (carousel) in three-dimensional space; in that arrangement, the last slide obviously comes before the first.
3-D transforms are more than just eye candy. We can also use them to solve dilemmas and make our applications more intuitive.

Current support

The CSS 3D Transforms module has been out in the wild for over a year now. Currently, only Safari supports the specification – which includes Safari on Mac OS X and Mobile Safari on iOS.
The support roadmap for other browsers varies. The Mozilla team has taken some initial steps towards implementing the module. Mike Taylor tells me that the Opera team is keeping a close eye on CSS transforms, and is waiting until the specification is fleshed out. And our best friend Internet Explorer still needs to catch up to 2-D transforms before we can talk about the 3-D variety.
To make matters more perplexing, Safari’s WebKit cousin Chrome currently accepts 3-D transform declarations, but renders them in 2-D space. Chrome team member Paul Irish, says that 3-D transforms are on the horizon, perhaps in one of the next 8.0 releases.
This all adds up to a bit of a challenge for those of us excited by 3-D transforms. I’ll give it to you straight: missing the dimension of depth can make degradation a bit ungraceful. Unless the transform is relatively simple and holds up in non-3D-supporting browsers, you’ll most likely have to design another solution. But what’s another hurdle in a steeplechase? We web folk have had our mettle tested for years. We’re prepared to devise multiple solutions.
Here’s the part of the article where I mention Modernizr, and you brush over it because you’ve read this part of an article hundreds of times before. But seriously, it’s the best way to test for CSS 3-D transform support. Use it.
Even with these difficulties mounting up, trying out 3-D transforms today is the right move. The CSS 3-D transforms module was developed by the same team at Apple that produced the CSS 2D Transforms and Animation modules. Both specifications have since been adopted by Mozilla and Opera. Transforming in three-dimensions now will guarantee you’ll be ahead of the game when the other browsers catch up.
The choice is yours. You can make excuses and pooh-pooh 3-D transforms because they’re too hard and only snobby Apple fans will see them today. Or, with a tip of the fedora to Mr Andy Clarke, you can get hard-boiled and start designing with the best features out there right this instant.
So, I bid you, in the words of the eternal Optimus Prime
Transform and roll out.
Let’s get coding.

Perspective

To activate 3-D space, an element needs perspective. This can be applied in two ways: using the transform property, with the perspective as a functional notation:
-webkit-transform: perspective(600);
or using the perspective property:
-webkit-perspective: 600;
See example: Perspective 1.
Perspective example The red element on the left uses transform: perspective() functional notation; the blue element on the right uses the perspective property
These two formats both trigger a 3-D space, but there is a difference. The first, functional notation is convenient for directly applying a 3-D transform on a single element (in the previous example, I use it in conjunction with a rotateY transform). But when used on multiple elements, the transformed elements don’t line up as expected. If you use the same transform across elements with different positions, each element will have its own vanishing point. To remedy this, use the perspective property on a parent element, so each child shares the same 3-D space.
See Example: Perspective 2.
Perspective example Each red box on the left has its own vanishing point within the parent container; the blue boxes on the right share the vanishing point of the parent container
The value of perspective determines the intensity of the 3-D effect. Think of it as a distance from the viewer to the object. The greater the value, the further the distance, so the less intense the visual effect. perspective: 2000; yields a subtle 3-D effect, as if we were viewing an object from far away. perspective: 100; produces a tremendous 3-D effect, like a tiny insect viewing a massive object.
By default, the vanishing point for a 3-D space is positioned at its centre. You can change the position of the vanishing point with perspective-origin property.
-webkit-perspective-origin: 25% 75%;
See Example: Perspective 3.
Intense perspective value, with vanishing point modified

3-D transform functions

As a web designer, you’re probably well acquainted with working in two dimensions, X and Y, positioning items horizontally and vertically. With a 3-D space initialised with perspective, we can now transform elements in all three glorious spatial dimensions, including the third Z dimension, depth.
3-D transforms use the same transform property used for 2-D transforms. If you’re familiar with 2-D transforms, you’ll find the basic 3D transform functions fairly similar.
  • rotateX(angle)
  • rotateY(angle)
  • rotateZ(angle)
  • translateZ(tz)
  • scaleZ(sz)
Whereas translateX() positions an element along the horizontal X-axis, translateZ() positions it along the Z-axis, which runs front to back in 3-D space. Positive values position the element closer to the viewer, negative values further away.
The rotate functions rotate the element around the corresponding axis. This is somewhat counter-intuitive at first, as you might imagine that rotateX will spin an object left to right. Instead, using rotateX(45deg) rotates an element around the horizontal X-axis, so the top of the element angles back and away, and the bottom gets closer to the viewer.
See Example: Transforms 1.
CSS 3D transform functions3-D rotate() and translate() functions around each axis
There are also several shorthand transform functions that require values for all three dimensions:
  • translate3d(tx,ty,tz)
  • scale3d(sx,sy,sz)
  • rotate3d(rx,ry,rz,angle)
Pro-tip: These foo3d() transform functions also have the benefit of triggering hardware acceleration in Safari. Dean Jackson, CSS 3-D transform spec author and main WebKit dude, writes (to Thomas Fuchs):
In essence, any transform that has a 3D operation as one of its functions will trigger hardware compositing, even when the actual transform is 2D, or not doing anything at all (such as translate3d(0,0,0)). Note this is just current behaviour, and could change in the future (which is why we don’t document or encourage it). But it is very helpful in some situations and can significantly improve redraw performance.
For the sake of simplicity, my demos will use the basic transform functions, but if you’re writing production-ready CSS for iOS or Safari-only, make sure to use the foo3d() functions to get the best rendering performance.

Card flip

We now have all the tools to start making 3-D objects. Let’s get started with something simple: flipping a card.
Here’s the basic markup we’ll need:
<section class="container">
  <div id="card">
    <figure class="front">1</figure>
    <figure class="back">2</figure>
  </div>
</section>
The .container will house the 3-D space. The #card acts as a wrapper for the 3-D object. Each face of the card has a separate element: .front; and .back. Even for such a simple object, I recommend using this same pattern for any 3-D transform. Keeping the 3-D space element and the object element(s) separate establishes a pattern that is simple to understand and easier to style.
We’re ready for some 3-D stylin’. First, apply the necessary perspective to the parent 3-D space, along with any size or positioning styles.
.container { 
  width: 200px;
  height: 260px;
  position: relative;
  -webkit-perspective: 800;
}
Now the #card element can be transformed in its parent’s 3-D space. We’re combining absolute and relative positioning so the 3-D object is removed from the flow of the document. We’ll also add width: 100%; and height: 100%;. This ensures the object’s transform-origin will occur in the centre of .container. More on transform-origin later.
Let’s add a CSS3 transition so users can see the transform take effect.
#card {
  width: 100%;
  height: 100%;
  position: absolute;
  -webkit-transform-style: preserve-3d;
  -webkit-transition: -webkit-transform 1s;
}
The .container’s perspective only applies to direct descendant children, in this case #card. In order for subsequent children to inherit a parent’s perspective, and live in the same 3-D space, the parent can pass along its perspective with transform-style: preserve-3d. Without 3-D transform-style, the faces of the card would be flattened with its parents and the back face’s rotation would be nullified.
To position the faces in 3-D space, we’ll need to reset their positions in 2-D with position: absolute. In order to hide the reverse sides of the faces when they are faced away from the viewer, we use backface-visibility: hidden.
#card figure {
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  -webkit-backface-visibility: hidden;
}
To flip the .back face, we add a basic 3-D transform of rotateY(180deg).
#card .front {
  background: red;
}
#card .back {
  background: blue;
  -webkit-transform: rotateY(180deg);
}
With the faces in place, the #card requires a corresponding style for when it is flipped.
#card.flipped {
  -webkit-transform: rotateY(180deg);
}
Now we have a working 3-D object. To flip the card, we can toggle the flipped class. When .flipped, the #card will rotate 180 degrees, thus exposing the .back face.
See Example: Card 1.
3D card flip transitionFlipping a card in three dimensions

Slide-flip

Take another look at the Weather App 3-D transition. You’ll notice that it’s not quite the same effect as our previous demo. If you follow the right edge of the card, you’ll find that its corners stay within the container. Instead of pivoting from the horizontal centre, it pivots on that right edge. But the transition is not just a rotation – the edge moves horizontally from right to left. We can reproduce this transition just by modifying a couple of lines of CSS from our original card flip demo.
The pivot point for the rotation occurs at the right side of the card. By default, the transform-origin of an element is at its horizontal and vertical centre (50% 50% or center center). Let’s change it to the right side:
#card { -webkit-transform-origin: right center; }
That flip now needs some horizontal movement with translateX. We’ll set the rotation to -180deg so it flips right side out.
#card.flipped {
  -webkit-transform: translateX(-100%) rotateY(-180deg);
}
See Example: Card 2.
3D card slide-flip transitionCreating a slide-flip from the right edge of the card

Cube

Creating 3-D card objects is a good way to get started with 3-D transforms. But once you’ve mastered them, you’ll be hungry to push it further and create some true 3-D objects: prisms. We’ll start out by making a cube.
The markup for the cube is similar to the card. This time, however, we need six child elements for all six faces of the cube:
<section class="container">
  <div id="cube">
    <figure class="front">1</figure>
    <figure class="back">2</figure>
    <figure class="right">3</figure>
    <figure class="left">4</figure>
    <figure class="top">5</figure>
    <figure class="bottom">6</figure>
  </div>
</section>
Basic position and size styles set the six faces on top of one another in the container.
.container {
  width: 200px;
  height: 200px;
  position: relative;
  -webkit-perspective: 1000;
}
#cube {
  width: 100%;
  height: 100%;
  position: absolute;
  -webkit-transform-style: preserve-3d;
}
#cube figure {
  width: 196px;
  height: 196px;
  display: block;
  position: absolute;
  border: 2px solid black;
}
With the card, we only had to rotate its back face. The cube, however, requires that five of the six faces to be rotated. Faces 1 and 2 will be the front and back. Faces 3 and 4 will be the sides. Faces 5 and 6 will be the top and bottom.
#cube .front { -webkit-transform: rotateY(0deg); }
#cube .back { -webkit-transform: rotateX(180deg); }
#cube .right { -webkit-transform: rotateY(90deg); }
#cube .left { -webkit-transform: rotateY(-90deg); }
#cube .top { -webkit-transform: rotateX(90deg); }
#cube .bottom { -webkit-transform: rotateX(-90deg); }
We could remove the first #cube .front style declaration, as this transform has no effect, but let’s leave it in to keep our code consistent.
Now each face is rotated, and only the front face is visible. The four side faces are all perpendicular to the viewer, so they appear invisible. To push them out to their appropriate sides, they need to be translated out from the centre of their positions. Each side of the cube is 200 pixels wide. From the cube’s centre they’ll need to be translated out half that distance, 100px.
#cube .front { -webkit-transform: rotateY(0deg) translateZ(100px); }
#cube .back { -webkit-transform: rotateX(180deg) translateZ(100px); }
#cube .right { -webkit-transform: rotateY(90deg) translateZ(100px); }
#cube .left { -webkit-transform: rotateY(-90deg) translateZ(100px); }
#cube .top { -webkit-transform: rotateX(90deg) translateZ(100px); }
#cube .bottom { -webkit-transform: rotateX(-90deg) translateZ(100px); }
Note here that the translateZ function comes after the rotate. The order of transform functions is important. Take a moment and soak this up. Each face is first rotated towards its position, then translated outward in a separate vector.
We have a working cube, but we’re not done yet.

Returning to the Z-axis origin

For the sake of our users, our 3-D transforms should not distort the interface when the active panel is at its resting position. But once we start pushing elements off their Z-axis origin, distortion is inevitable.
In order to keep 3-D transforms snappy, Safari composites the element, then applies the transform. Consequently, anti-aliasing on text will remain whatever it was before the transform was applied. When transformed forward in 3-D space, significant pixelation can occur.
See Example: Transforms 2.
Using 3D transforms can pixelate text
Looking back at the Perspective 3 demo, note that no matter how small the perspective value is, or wherever the transform-origin may be, the panel number 1 always returns to its original position, as if all those funky 3-D transforms didn’t even matter.
To resolve the distortion and restore pixel perfection to our #cube, we can push the 3-D object back, so that the front face will be positioned back to the Z-axis origin.
#cube { -webkit-transform: translateZ(-100px); }
See Example: Cube 1.
CSS 3D cube objectRestoring the front face to the original position on the Z-axis

Rotating the cube

To expose any face of the cube, we’ll need a style that rotates the cube to expose any face. The transform values are the opposite of those for the corresponding face. We toggle the necessary class on the #box to apply the appropriate transform.
#cube.show-front { -webkit-transform: translateZ(-100px) rotateY(0deg); }
#cube.show-back { -webkit-transform: translateZ(-100px) rotateX(-180deg); }
#cube.show-right { -webkit-transform: translateZ(-100px) rotateY(-90deg); }
#cube.show-left { -webkit-transform: translateZ(-100px) rotateY(90deg); }
#cube.show-top { -webkit-transform: translateZ(-100px) rotateX(-90deg); }
#cube.show-bottom { -webkit-transform: translateZ(-100px) rotateX(90deg); }
Notice how the order of the transform functions has reversed. First, we push the object back with translateZ, then we rotate it.
Finishing up, we can add a transition to animate the rotation between states.
#cube { -webkit-transition: -webkit-transform 1s; }
See Example: Cube 2.
CSS 3D cube object changing sidesRotating the cube with a CSS transition

Rectangular prism

Cubes are easy enough to generate, as we only have to worry about one measurement. But how would we handle a non-regular rectangular prism? Let’s try to make one that’s 300 pixels wide, 200 pixels high, and 100 pixels deep.
The markup remains the same as the #cube, but we’ll switch the cube id for #box. The container styles remain mostly the same:
.container {
  width: 300px;
  height: 200px;
  position: relative;
  -webkit-perspective: 1000;
}
#box {
  width: 100%;
  height: 100%;
  position: absolute;
  -webkit-transform-style: preserve-3d;
}
Now to position the faces. Each set of faces will need their own sizes. The smaller faces (left, right, top and bottom) need to be positioned in the centre of the container, where they can be easily rotated and then shifted outward. The thinner left and right faces get positioned left: 100px ((300 − 100) ÷ 2), The stouter top and bottom faces get positioned top: 50px ((200 − 100) ÷ 2).
#box figure {
  display: block;
  position: absolute;
  border: 2px solid black;
}
#box .front,
#box .back {
  width: 296px;
  height: 196px;
}
#box .right,
#box .left {
  width: 96px;
  height: 196px;
  left: 100px;
}
#box .top,
#box .bottom {
  width: 296px;
  height: 96px;
  top: 50px;
}
The rotate values can all remain the same as the cube example, but for this rectangular prism, the translate values do differ. The front and back faces are each shifted out 50 pixels since the #box is 100 pixels deep. The translate value for the left and right faces is 150 pixels for their 300 pixels width. Top and bottom panels take 100 pixels for their 200 pixels height:
#box .front { -webkit-transform: rotateY(0deg) translateZ(50px); }
#box .back { -webkit-transform: rotateX(180deg) translateZ(50px); }
#box .right { -webkit-transform: rotateY(90deg) translateZ(150px); }
#box .left { -webkit-transform: rotateY(-90deg) translateZ(150px); }
#box .top { -webkit-transform: rotateX(90deg) translateZ(100px); }
#box .bottom { -webkit-transform: rotateX(-90deg) translateZ(100px); }
See Example: Box 1.
3D CSS box object
Just like the cube example, to expose a face, the #box needs to have a style to reverse that face’s transform. Both the translateZ and rotate values are the opposites of the corresponding face.
#box.show-front { -webkit-transform: translateZ(-50px) rotateY(0deg); }
#box.show-back { -webkit-transform: translateZ(-50px) rotateX(-180deg); }
#box.show-right { -webkit-transform: translateZ(-150px) rotateY(-90deg); }
#box.show-left { -webkit-transform: translateZ(-150px) rotateY(90deg); }
#box.show-top { -webkit-transform: translateZ(-100px) rotateX(-90deg); }
#box.show-bottom { -webkit-transform: translateZ(-100px) rotateX(90deg); }
See Example: Box 2.
3D CSS box object rotatingRotating the rectangular box with a CSS transition

Carousel

Front-end developers have a myriad of choices when it comes to content carousels. Now that we have 3-D capabilities in our browsers, why not take a shot at creating an actual 3-D carousel?
The markup for this demo takes the same form as the box, cube and card. Let’s make it interesting and have a carousel with nine panels.
<div class="container">
  <div id="carousel">
    <figure>1</figure>
    <figure>2</figure>
    <figure>3</figure>
    <figure>4</figure>
    <figure>5</figure>
    <figure>6</figure>
    <figure>7</figure>
    <figure>8</figure>
    <figure>9</figure>
  </div>
</div>
Now, apply basic layout styles. Let’s give each panel of the #carousel 20 pixel gaps between one another, done here with left: 10px; and top: 10px;. The effective width of each panel is 210 pixels.
.container {
  width: 210px;
  height: 140px;
  position: relative;
  -webkit-perspective: 1000;
}
#carousel {
  width: 100%;
  height: 100%;
  position: absolute;
  -webkit-transform-style: preserve-3d;
}
#carousel figure {
  display: block;
  position: absolute;
  width: 186px;
  height: 116px;
  left: 10px;
  top: 10px;
  border: 2px solid black;
}
Next up: rotating the faces. This #carousel has nine panels. If each panel gets an equal distribution on the carousel, each panel would be rotated forty degrees from its neighbour (360 ÷ 9).
#carousel figure:nth-child(1) { -webkit-transform: rotateY(0deg); }
#carousel figure:nth-child(2) { -webkit-transform: rotateY(40deg); }
#carousel figure:nth-child(3) { -webkit-transform: rotateY(80deg); }
#carousel figure:nth-child(4) { -webkit-transform: rotateY(120deg); }
#carousel figure:nth-child(5) { -webkit-transform: rotateY(160deg); }
#carousel figure:nth-child(6) { -webkit-transform: rotateY(200deg); }
#carousel figure:nth-child(7) { -webkit-transform: rotateY(240deg); }
#carousel figure:nth-child(8) { -webkit-transform: rotateY(280deg); }
#carousel figure:nth-child(9) { -webkit-transform: rotateY(320deg); }
Now, the outward shift. Back when we were creating the cube and box, the translate value was simple to calculate, as it was equal to one half the width, height or depth of the object. With this carousel, there is no size we can automatically use as a reference. We’ll have to calculate the distance of the shift by other means.
Geometric diagram of carousel
Drawing a diagram of the carousel, we can see that we know only two things: the width of each panel is 210 pixels; and the each panel is rotated forty degrees from the next. If we split one of these segments down its centre, we get a right-angled triangle, perfect for some trigonometry.
We can determine the length of r in this diagram with a basic tangent equation:
Trigonometric calculation
There you have it: the panels need to be translated 288 pixels in 3-D space.
#carousel figure:nth-child(1) { -webkit-transform: rotateY(0deg) translateZ(288px); }
#carousel figure:nth-child(2) { -webkit-transform: rotateY(40deg) translateZ(288px); }
#carousel figure:nth-child(3) { -webkit-transform: rotateY(80deg) translateZ(288px); }
#carousel figure:nth-child(4) { -webkit-transform: rotateY(120deg) translateZ(288px); }
#carousel figure:nth-child(5) { -webkit-transform: rotateY(160deg) translateZ(288px); }
#carousel figure:nth-child(6) { -webkit-transform: rotateY(200deg) translateZ(288px); }
#carousel figure:nth-child(7) { -webkit-transform: rotateY(240deg) translateZ(288px); }
#carousel figure:nth-child(8) { -webkit-transform: rotateY(280deg) translateZ(288px); }
#carousel figure:nth-child(9) { -webkit-transform: rotateY(320deg) translateZ(288px); }
If we decide to change the width of the panel or the number of panels, we only need to plug in those two variables into our equation to get the appropriate translateZ value. In JavaScript terms, that equation would be:
var tz = Math.round( ( panelSize / 2 ) / 
  Math.tan( ( ( Math.PI * 2 ) / numberOfPanels ) / 2 ) );
// or simplified to
var tz = Math.round( ( panelSize / 2 ) / 
  Math.tan( Math.PI / numberOfPanels ) );
Just like our previous 3-D objects, to show any one panel we need only apply the reverse transform on the carousel. Here’s the style to show the fifth panel:
-webkit-transform: translateZ(-288px) rotateY(-160deg);
See Example: Carousel 1.
3-D CSS carousel
By now, you probably have two thoughts:
  1. Rewriting transform styles for each panel looks tedious.
  2. Why bother doing high school maths? Aren’t robots supposed to be doing all this work for us?
And you’re absolutely right. The repetitive nature of 3-D objects lends itself to scripting. We can offload all the monotonous transform styles to our dynamic script, which, if done correctly, will be more flexible than the hard-coded version.
See Example: Carousel 2.

Conclusion

3-D transforms change the way we think about the blank canvas of web design. Better yet, they change the canvas itself, trading in the flat surface for voluminous depth.
My hope is that you took at least one peak at a demo and were intrigued. We web designers, who have rejoiced for border-radius, box-shadow and background gradients, now have an incredible tool at our disposal in 3-D transforms. They deserve just the same enthusiasm, research and experimentation we have seen on other CSS3 features. Now is the perfect time to take the plunge and start thinking about how to use three dimensions to elevate our craft. I’m breathless waiting for what’s to come.
See you on the flip side.

New form features in HTML5

Introduction

HTML5 includes many new features to make web forms a lot easier to write, and a lot more powerful and consistent across the Web. This article gives a brief overview of some of the new form controls and functionalities that have been introduced.

Bad form?

Let's face it – HTML forms have always been a pain. They are not much fun to mark up and they can be fiddly to style – especially if you want them to be consistent cross-browser and fit in with the overall look and feel of your site. And they can be frustrating for your end users to fill out, even if you create them with care and consideration to make them as usable and accessible as possible. Creating a good form is more about damage limitation than pleasurable user experiences.
Back when HTML 4.01 became a stable recommendation, the web was a mostly static place. Yes, there was the odd comment form or guest book script, but generally web sites were there for visitors to simply read. Since then, the web has evolved. For many people, the browser has already become a window into a world of complex, web-based applications that try to bring an almost desktop-like experience.
Some complicated non-native form controls, faked with JavaScript
Figure 1: Some complicated non-native form controls, faked with JavaScript.
To fill the need for the more sophisticated controls required for such applications, developers have been taking advantage of JavaScript libraries and frameworks (such as jQueryUI or YUI). These solutions have certainly matured over the years, bringing rich functionality to web pages and even starting to incorporate screenreader support through bridging technologies like WAI-ARIA. But essentially, they're a workaround to compensate for the limited form controls available in HTML. They “fake” the more complex widgets (such as date pickers and sliders) by layering additional (not always semantic) markup and a slew of JavaScript on top of pages.
HTML5 aims to standardise some of the most common rich form controls, making them render natively in the browser and obviating the need for these script-heavy workarounds.

Introducing our example

To illustrate some of the new features, this article comes with a basic HTML5 forms example. It's not meant to represent a "real" form (as you'd be hard-pressed to find a situation where you need all the new features in a single form), but it should give you an idea of how the various new aspects look and behave.
Note: the look and feel of the new form controls and validation messages differs from brower to browser, so styling your forms to look reasonably consistent across browsers will still need careful consideration.

New form controls

As forms are the main tool for data input in Web applications, and the data we want to collect has become more complex, it has been necessary to create an input element with more capabilities, to collect this data with more semantics and better definition, and allow for easier, more effective error mnagement and validation.

<input type="number">

The first new input type we'll discuss is the number type:
<input type="number" … >
This creates a special kind of input field for number entry – in most supporting browsers this appears as a text entry field with a spinner control, which allows you to increment and decrement its value.
A number input type
Figure 2: A number input type.

<input type="range">

Creating a slider control to allow you to choose between a range of values used to be a complicated, semantically dubious proposition, but with HTML5 it is easy — you just use the range input type:
<input type="range" … >
A range input type
Figure 3: A range input type.
Note that, by default, this input does not generally show the currently selected value, or even the range of values it covers. Authors will need to provide these through other means – for instance, to display the current value, we could us an output element together with some JavaScript to update its display whenever the user has interacted with the form:
<output onforminput="value=weight.value"></output>

<input type="date"> and other date/time controls

HTML5 has a number of different input types for creating complicated date/time pickers, for example the kind of date picker you see featured on pretty much every flight/train booking site out there. These used to be created using unsemantic kludges, so it is great that we now have standardized easy ways to do this. For example:
<input type="date" … >
<input type="time" … >
Respectively, these create a fully functioning date picker, and a text input containing a separator for hours, minutes and seconds (depending on the step attribute specified) that only allows you to input a time value.
date and time input types
Figure 4: date and time input types.
But it doesn't end here — there are a number of other related input types available:
  • datetime: combines the functionality of two we have looked at above, allowing you to choose a date and a time
  • month: allows you to choose a month, stored internally as a number between 1-12, although different browsers may provide you with more elaborate choosing mechanisms, like a scrolling list of the month names
  • week: allows you to choose a week, stored internally in the format 2010-W37 (week 37 of the year 2010), and chosen using a similar datepicker to the ones we have seen already

<input type="color">

This input type brings up a color picker. Opera's implementation allows the user to pick from a selection of colors, enter hexadecimal values directly in a text field, or to invoke the OS's native color picker.
a color input, and the native color pickers on Windows and OS X
Figure 5: a color input, and the native color pickers on Windows and OS X.
The search input type is arguably nothing more than a differently-styled text input. Browsers are meant to style these inputs the same way as any OS-specific search functionality. Beyond this purely aesthetic consideration, though, it's still important to note that marking up search fields explicitly opens up the possibility for browsers, assistive technologies or automated crawlers to do something clever with these inputs in the future – for instance, a browser could conceivably offer the user a choice to automatically create a custom search for a specific site.
A search input as it appears in Opera on OS X
Figure 6: A search input as it appears in Opera on OS X.

<datalist> element and list attribute

Up until now we have been used to using <select> and <option> elements to create dropdown lists of options for our users to choose from. But what if we wanted to create a list that allowed users to choose from a list of suggested options, as well as being able to type in their own? That required fiddly scripting – but now you can simply use the list attribute to connect an ordinary input to a list of options, defined inside a <datalist> element.
<input type="text" list="mydata" … >
<datalist id="mydata">
    <option label="Mr" value="Mister">
    <option label="Mrs" value="Mistress">
    <option label="Ms" value="Miss">
</datalist>
Creating an input element with preset options using datalist
Figure 7: Creating an input element with suggestions using datalist.

<input type="tel">, <input type="email"> and <input type="url">

As their names imply, these new input types relate to telephone numbers, email addresses or URLs. Browsers will render these as normal text entry inputs, but explicitly stating what kind of text we're expecting in these fields plays an important role in client-side form validation. Additionally, on certain mobile devices the browser will switch from its regular text entry on-screen keyboard to the more context-relevant variants. Again, it's conceivable that in the future browsers will take further advantage of these explicitly marked-up inputs to offer additional functionality, such as autocompleting email addresses and telephone numbers based on the user's contacts list or address book.

New attributes

In addition to explicit new input types, HTML5 defines a series of new attributes for form controls that help simplify some common tasks and further specify the expected values for certain entry fields.

placeholder

A common usability trick in web forms is to have placeholder content in text entry fields – for instance, to give more information about the expected type of information we want the user to enter – which disappears when the form control gets focus. While this used to require some JavaScript (clearing the contents of the form field on focus and resetting it to the default text if the user left the field without entering anything), we can now simply use the placeholder attribute:
<input type="text"placeholder="John Doe">
A text input with placeholder text
Figure 8: A text input with placeholder text.

autofocus

Another common feature that previously had to rely on scripting is having a form field automatically focused when a page is loaded. This can now be achieved with the autofocus attribute:
<input type="text" autofocus … >
Keep in mind that you shouldn't have more than one autofocus form control on a single page. You should also use this sort of functionality with caution, in situations where a form represents the main area of interest in a page. A search page is a good example – provided that there isn't a lot of content and explanatory text, it makes sense to set the focus automatically to the text input of the search form.

min and max

As their name suggests, this pair of attributes allows you to set a lower and upper bound for the values that can be entered into a numerical form field, for example number, range, time or date input types (yes, you can even use it to set upper and lower bounds for dates – for instance, on a travel booking form you could limit the datepicker to only allow the user to select future dates). For range inputs, min and max are actually necessary to define what values are returned when the form is submitted. The code is pretty simple and self-explanatory:
<input type="number"min="1" max="10">

step

The step attribute can be used with a numerical input value to dictate how granular the values you can input are. For example, you might want users to enter a particular time, but only in 30 minute increments. In this case, we can use the step attribute, keeping in mind that for time inputs the value of the attribute is in seconds:
<input type="time"step="1800">

New output mechanisms

Beyond the new form controls that users can interact with, HTML5 defines a series of new elements specifically meant to display and visualise information to the user.

<output>

We've already mentioned the output element when talking about the range input – this element serves as a way to display the result of a calculation, or more generally to provide an explicitly identified output of a script (rather than simply pushing some text into in a random span or div with innerHTML, for instance). To make it even more explicit what particular form controls the output relates to, we can – in a similar way to label – pass a list of IDs in the element's optional for attribute.

<input type="range" id="rangeexample" … >
<output onforminput="value=rangeexample.value" for="rangeexample"></output>

<progress> and <meter>

These two new elements are very similar, both resulting in a gauge/bar being presented to the user. Their distinction is in their intended purpose. As the name suggests, progress is meant to represent a progress bar, to indicate the percentage of completion of a particular task, while meter is a more generic indicator of a scalar measurement or fractional value.
A progress indicator bar
Figure 9: A progress indicator bar.

Validation

Form validation is very important on both client- and server-side, to help legitimate users avoid and correct mistakes, and to stop malicious users submitting data that could cause damage to our application. As browsers can now get an idea of what type of values are expected from the various form controls (be it their type, or any upper/lower bounds set on numerical values, dates and times), they can also offer native form validation – another tedious task that, up to now, required authors to write reams of JavaScript or use some ready-made validation script/library.
Note: for form controls to be validated, they need to have a name attribute, as without it they wouldn't be submitted as part of the form anyway.

required

One of the most common aspects of form validation is the enforcement of required fields – not allowing a form to be submitted until certain pieces of information have been entered. This can now simply be achieved by adding the required attribute to an input, select or textarea element.
<input type="text"required>
Opera's client-side validation in action, showing an error for a required field that was left empty
Figure 10: Opera's client-side validation in action, showing an error for a required field that was left empty.

type and pattern

As we've seen, authors can now specify the kinds of entries they expect from their form fields – rather than simply defining text inputs, authors can explicitly create inputs for things like numbers, email addresses and URLs. As part of their client-side validation, browsers can now check that what the user entered in these more specific fields matches the expected structure – in essence, browsers evaluate the input values against a built-in pattern that defines what valid entires in those types of inputs look like, and will warn a user when their entry didn't match the criteria.
Opera's error message for invalid email addresses in an email input
Figure 11: Opera's error message for invalid email addresses in an email input.
For other text entry fields that nonetheless need to follow a certain structure (for instance, login forms where the usernames can only contain a specific sequence of lowercase letters and numbers), authors can use the pattern attribute to specify their own custom regular expression.
<input type="text"pattern="[a-z]{3}[0-9]{3}">

Styling with CSS3

In concert with HTML5's built-in form validation, the CSS3 Basic User Interface Module defines a series of new pseudo-classes that can be used to differentiate required fields and to change the appearance of form controls dynamically based on whether or not they have been filled in correctly:
  • :required and :optional let us explicitly style controls based on whether or not they have a required attribute
  • :valid and :invalid will apply styles to form controls subject to client-side validation
  • :in-range and :out-of-range specifically works with controls that feature a min and/or max attribute
In our example form, we're only applying specific validity and range styles on text, email, url and number inputs when they are currently focused, so users would get some immediate visual feedback while entering information into those fields, but without affecting the overall look of the form in general.
input[type=text]:focus:valid,
input[type=email]:focus:valid,
input[type=number]:focus:in-range { outline: 2px #0f0 solid; }

input[type=text]:focus:invalid,
input[type=email]:focus:invalid,
input[type=number]:focus:out-of-range { outline: 2px #f00 solid; }
:focus:valid and :focus:invalid styles being applied dynamically as an email address is entered
Figure 12: :valid and :invalid styles being applied dynamically as an email address is entered.

Cross browser?

On the desktop, Opera currently has the most complete implementation of new input types and native client-side validation, but support is on the roadmap for all other major browsers as well, so it won't be long before we can take advantage of these new powerful tools in our projects. But what about older browser versions?
By design, browsers that don't understand the new input types (like date or number) will simply fall back to treating them as standard text inputs – not as user-friendly as their advanced HTML5 counterparts, but at the very least they allow for a form to be filled in. However, as with most of the new HTML5 functionalities, we can offer a nicer fallback for users of browsers that aren't quite up to speed with HTML5 forms by doing basic JavaScript-based feature-detection and, only if needed, proceed to load external JavaScript libraries to “fake” the support for more complex form control widgets and validation. This way, we can code for the future, while not alienating any of our users.