Get the Code You Need (without the typing).
Follow the links below to find code samples from the book, iPhone & iPad Web Design For Dummies by Janine Warner, David LaFontaine & Lee Andron
For HTML Code from Chapters 4 or 5:
- How to use CSS Media Queries to target the iPhone and iPad
- Copy and Paste code to create a simple HTML 5 page
- Code for a more complete HTML page ready your content
- How to add audio and video to mobile web pages
- Creating the Ultimate Contact Page with HTML5
- Bonus: How is HTML5 changing mobile web site design?
For HTML Code from Chapters 6 or 7:
Scroll down to find the complete contents of these two chapters so you can copy and paste the code, as needed.
Tip: Make Phone Numbers Easy to Dial
Also note, here is the correct way to turn a phone number into a link that can be touch-dialed from nearly any phone:
<a href=”tel:18001234567″>+1-800-123-4567</a>
The Jellyfish Website
If you’re looking for the Jellyfish site, we’re making the entire site available for download, but please note, this final version of the site includes code that is not covered in the For Dummies book. We hope you can use this site as an example to study and learn from, but please understand that some of the more advanced aspects of this site were too complicated to cover in a For Dummies book.
Download zip file with the entire Jellyfish mobile website by clicking here.
Chapter 6: Designing with the Advantages of CSS3
Copy the code featured in Chapter 6 from this digitized version.
In This Chapter
* Showing off CSS 3 in the most current browsers
* Designing with style
* Enhancing site designs
* Creating gradients, drop shadows, and more with CSS3
* Targeting styles with media queries
* Hiding extra info from small screens
* Troubleshooting how styles cascade
Many designers are excited about the new features in CSS 3, including the ability to use almost any font on your web pages, to add drop shadows to text and other elements, and to create gradients — without resorting to using images. These long-awaited design improvements offer a compelling reason to start using CSS 3 right away.
In addition to new design options, CSS 3 offers the ability to target specific devices with styles — you can create style sheets targeting the iPhone, the iPad, and the desktop, and devices. CSS 3 also adds styles that create animation, interactivity effects and transitions that were previously possible only by using a program such as Adobe Flash.
In this chapter, we introduce the most popular CSS 3 features, including the ability to add drop shadows to text and created rounded corners so that you can immediately start designing pages with CSS 3. In the next chapter, we get into more advanced CSS 3 features and show you how to combine JavaScript with CSS to create more-complex design features.
In Figure 6-1, you can see how we’ve used media queries to alter the design of the page about oceanographer Mark Loos based on the orientation of the iPad, by displaying a wider design when the iPad is in landscape mode than when it’s in portrait mode.
In Chapter 5, you discover how to create a web page framework by designing a document using the latest in HTML5 tags. In this chapter, you add the style that makes the page look good on each device.
Displaying New Code in Many Browsers
Apple created the operating system, iOS, which runs on the iPhone, iPad and iPod touch and in a special version in Apple TV 2. Safari, the default iOS browser, supports nearly the entire CSS specification as described by the World Wide Web Consortium (W3C). The W3C is an open international organization that develops web standards led by the inventor of the web, Tim Berners-Lee. They bring together browser creators, leaders and users to create the specifications for the protocols that define the World Wide Web.
Similar to HTML5, CSS 3 is still under development as we write this book. The specification will not reach its final stage of “Proposed Recommendation” until 2022, according to the W3C’s timeline. Even if the specification may not be final for many years browser developers typically implement parts of the working drafts of new versions of HTML and CSS as they update their browsers. When they implement parts of a working draft they call it experimental CSS and they usually put the browser name in the rule. That’s why there are multiple versions of the same style rules, as you see in the example for creating rounded corners in the next section.
Many designers shy away from experimental CSS, preferring to wait until the standards are approved or at least, most web browsers support them consistently. It’s easier when every browser plays by the same rules and implementing experimental CSS can lead to problems if the specification is changed again in the future. However, CSS 3 offers so many exciting new features and so few negative side effects — if you design your pages carefully — that you have little reason to hold back. CSS naturally degrades in browsers. (If the browser doesn’t support a CSS style, it’s ignored.)
When you focus a design on the iPhone, iPod touch, or iPad, you have the advantage of knowing that your visitors will be using the Safari web browser. It’s based on the WebKit layout engine, which can render CSS 3 as well as any desktop browser can. WebKit is also used in Google Chrome. Thus, most sites that look good in Safari for the desktop also look good in Chrome (although like most things in web design, you might see exceptions).
In this book, we focus on designing for the iPhone iPod Touch and iPad, by showing you how to create pages that display well in the desktop Safari browser versions 3 and 4. However, we assume that most of you still have to work in the real world and that not all visitors to your sites may be using Safari. To create CSS 3 styles that work in Firefox or Internet Explorer or another browser, you may need to add special code for those browsers. For tips on how to make your designs display well on more than just WebKit browsers such as Safari, see the upcoming sections.
Making your CSS 3 work across browsers
If you’re designing for the desktop as well as for the iPhone and iPad, you can still use the experimental CSS 3! Eventually, the CSS 3 in your site will likely be supported. The example in this section shows you how to hedge your bets for the future. For any of the -webkit- code examples in this book (that cover our beloved Safari version 3.x and 4.x), create another identical CSS rule with -moz- to cover Firefox and one CSS rule with just the root name to cover the newest browsers: Opera 10.5, Internet Explorer 9, Safari 5, Chrome, and future browsers.
Here is an example of a set of rules to round the corners of a box:
-webkit-border-radius: 12px; /* Saf3-4 */
-moz-border-radius: 12px; /* FF1+ */
border-radius: 12px; /* Opera 10.5, IE 9, Saf5, Chrome */
Resetting HTML Elements with CSS
The new semantic tags in HTML5 work well in Safari on the iPhone and iPad, but not in most of the older web browsers that are still common on the web. To make these new elements work in older browsers, all you have to do is set the style rules for display to block to define the semantic tags as block-level elements. That makes them act like <div> tags in older browsers.
Because not all browsers interpret HTML and CSS in the same way, many web developers begin designing pages by creating styles that remove any border, padding, or margins included in an HTML tag by defining a style that sets those values to 0 (as you see in the following example).
The process of resetting elements helps ensure that any styles you create will display more consistently across different web browsers because all your tags start with the same blank slate. It’s good practice for Safari on the iPad and iPhone, as well as for other browsers.
In this example, we’ve set the display to block and simultaneously set the border, padding, and margins to 0 to ensure a more consistent display across different web browsers:article, aside, footer, header, menu, nav, section, details, table, body, h1, h2, h3, p, ul, li, {
border:0; margin:0; padding:0;
display: block;
Styling Text with CSS 3
When you create CSS 3 for an iPhone or iPad site, you not only enjoy the benefits of custom fonts and drop shadows but also gain the challenge of how to size text on screens of different dimensions. Worry no more: In this section, you find out how to best manage the sizing of text and then discover the joys of styling text by using CSS 3.
Adjusting text size
To help make it easier to read text on the iPhone, the default setting for the text-size-adjust rule is auto: The text is automatically scaled to the screen. On the iPad, the default is none because the larger screen doesn’t require text to be resized automatically. On many web sites, this adjustment makes the page easier to read, but if you’ve carefully designed your pages and targeted your styles specifically to the iPhone or iPad, you may want to prevent automatic resizing.
Here are three examples of how you can use this option:
-webkit-text-size-adjust: auto;
-webkit-text-size-adjust: none;
-webkit-text-size-adjust: 80%;
Here’s the code we build on in the preceding two sections, with the addition of the webkit-text-size-adjust rule set to none; including this bit of code in the style for all these tags at one time makes none of the text in the tags automatically resize:
/* This style helps older browsers understand HTML5 and resets common tags to 0 */
article, aside, footer, header, menu, nav, section, details,body, h1, h2, h3, p, ul, li, {
border:0;
margin:0;
padding:0;
display: block;
/* stops WebKit resizing text */
-webkit-text-size-adjust: none;
}
Understanding CSS size options
As in previous versions of CSS, you can specify sizes for fonts and other elements in so many ways that confusion can set in. If you’re familiar with print, you probably recognize point sizes and pixel sizes, but these aren’t necessarily the best options when you’re designing for the Internet. On the web, where display windows can vary from giant monitors to tiny cellphone screens, using relative sizes can help you create more flexible and adaptable designs — something you can’t do as well with fixed pixel or point sizes. As you work in Dreamweaver to create web pages, be sure to become familiar with the sizing options described in this list:
* Percentage-based relative sizes: You can use percentages to make text larger or smaller, relative to the base size. For example, you can define the text in a caption style as 90 percent so that your caption text appears at 90 percent of the size of the rest of the text on the page. You can then make headlines 150 percent (for example) and subheads 125 percent.
* Em and ex: Another size option is em, which refers to the space taken up by a capital letter M in the font face specified in a style. The ex option is similar, but it’s based on the size of a lowercase x in the specified font face. Although these two options may seem complex (especially when you’re new to web design), these two sizes are highly recommended, especially when you’re creating designs where the text may be resized because the size is adjusted relative to the displayed text size. Although this concept can get confusing, em and ex work much like percentages — and adapt even better to different user settings and monitor sizes.
Many web designers prefer the em and ex size options, especially when they specify text size, because these size options adjust well when the text size is altered by users or by device differences.
Adding text shadows
Using CSS 3, you can add drop shadows to text and to any block-level element, such as a <div> tag. We explain adding shadows to text in this section and cover block-level elements later in this chapter.
A helpful way to increase the contrast between text and the background is to add a text shadow. (See Figures 6-4 and 6-5 for examples of text with drop shadows created using CSS 3.) Text shadows not only make your page designs more interesting but also make text much more readable, especially if your design has a complex background or the foreground and background colors don’t have much contrast.
Here’s the syntax for text shadows for WebKit browsers:
text-shadow: horizontal vertical blur radius color;
Here’s how filling in these placeholders impacts the text shadow:
* horizontal and vertical: The first two values, which specify the horizontal and vertical offsets, are required. They specify the distance the drop shadow extends below and to the right of the text.
* blur radius: The third setting, which specifies the amount of blur in the shadow, is optional. If you don’t include a blur radius, the default is 0, which makes the specified color appear as a solid color.
* color: Specify a color using its hexadecimal color code (the traditional 6-character color codes) or its RGBa color code, which enables you to specify among red, green, and blue as well as opacity.
The following line of code adds a text shadow to the <h1> tag. The numbers specify that the text shadow extends two pixels to the right and below the text with a 3-pixel blur. This example uses a gray color specified with the hexadecimal color code #999
h1 {text-shadow: 2px 2px 3px #999;}
If you specify the color as an RGBa color, you can define a partially transparent color. RGBa colors are defined by a series of numbers that specify how much red, blue, or green you want. The range of numbers is 0 to 255. The fourth number defines the amount of opacity or transparency. (The range is 1 for full opacity to 0 for full transparency.) For example the .6 in the following example indicates an opacity level of 60 percent; 40 percent of the underlying color shines through.
The style defined for the <h1> tag above will apply to any text formatted with the heading 1 tag. The style below is a class style (incidated by the dot before the name). Class styles are more versatile and can be applied to any text on a page.
.shadow {text-shadow: .2em .2em .3em rgba(153,153,153,.6);}
In CSS, sizes can be specified in many different measurements, including pixels, percentages, and the em option used in the preceding example. For more on sizes, see the earlier sidebar “Understanding CSS size options.”
Enhancing your site with custom fonts
To most web designers, the font of fonts does not runneth over. The 11 fonts built into the Apple iOS, shown in Figure 6-2, are woefully inadequate. Serious designers spend hours searching for just the right font to convey the feeling they want to elicit in a design. That’s why many designers are excited that CSS 3 offers a new solution.
Figure 6-2: By default, Apple iOS limits designers to these 11 fonts.
The @font-face option, new in CSS 3, enables you to link to any font that’s available from a web server. Add a little drop shadow and other styling elements with CSS, and you can create fantastic font effects without resorting to the old workaround for limited fonts: saving images of styled text created in Photoshop.
Finding fonts online
Although you can upload any font you have to your own server and link to it, an online font repository offers many advantages, the font is stored on their servers and they provide the CSS to include the font in your site. Online font repositories also take care of any licensing issues. Fonts, much like images, are generally protected by copyright law; be sure that you have permission before uploading a font and making it available on the web.
We recommend you start by using the fonts available from the Google Font Directory or from FontSquirrel.com, as described in this list:
* Google Font Directory: The Google Font Directory (see Figure 6-7) makes it easy to use any of the fonts in the directory on your web pages. In the section that follow, you find detailed instructions for using a font from the Google Font Directory in your page designs.
* FontSquirrel: FontSquirrel.com makes it easy to use any number of free fonts on your web pages. Essentially, the folks at FontSquirrel have collected all the best free fonts (again- no worries about licensing issues). To include one of their free fonts, just download a font-face kit. It includes sample code and the 4 types of fonts needed to support browsers that currently implement the @font-face part of CSS3.
FontSquirrel also has one of the best font generators online. If you have a custom font, use the font generator to generate the 4 font types and the code you need in order to use any font on your web pages.
For instance, when we created a site for Intel we put their font through the generator on FontSquirrel, and then we were able to use their custom created “Intel font” rather than an image of their logo. Note: FontSquirrel requires that you have permission to use a font before you upload it and run it through its generator.
The Apple iOS supports True Type Fonts (TTF) and Scalable Vector Graphics (SVG) versions of a font. SVG and TTF are vector based, which means they can be scaled up or down with no loss of quality, making them an ideal choice when designing for the iPhone and iPad. TTF files are generally smaller, so we prioritize TTF higher than an SVC. If your user is using iOS older than 4.2 then the device will download and use the SVG automatically rather than the TTF.
Using fonts in your page designs
After you generate the code you need on FontSquirrel, you can start using the font on your web pages in a few simple steps. Below is an example of the code you would get if you ran a custom font through FontSquirrel. First, you add the font to the head area of your page by using the following syntax :
@font-face {
font-family: ‘GoodDogRegular’;
src: url(‘GoodDog-webfont.eot’);
src: url(‘GoodDog-webfont.eot?iefix’) format(‘eot’),
url(‘GoodDog-webfont.woff’) format(‘woff’),
url(‘GoodDog-webfont.ttf’) format(‘truetype’),
url(‘GoodDog-webfont.svg#webfontx1QlgLst’) format(‘svg’);
font-weight: normal;
font-style: normal;
}
Then you include the font in a style rule, and you can apply it to any text on your page.
.stylename {
font-family: ‘GoodDogRegular’;
}
Follow these steps to add any of the fonts in the Google Font Directory to your pages:
1. Open any web browser (we recommend Safari: the desktop version is closest to the version in iOS) and visit http://code.google.com/webfonts.
2. Click the name of any font to select the font you want to use in your design.
3. Click the Use This Font tab at the top of the page to generate the code you need, as shown in Figure 6-3.
Figure 6-3: The Google Font Directory makes it easy to generate the code you need to use a growing collection fonts in your web pages.
4. Copy the link in the first field and paste it into the head area of your web page.
5. Copy the code for the font family from the second field on the Google Font Directory font page (also shown in Figure 6-3) and paste it into the CSS style sheet for your web page.
In the example shown in Figure 6-3, you see that Google has generated the rule in a style for the <h1> tag. You can use this code to create a style for the <h1> tag with the font you selected, but you also have the option of adding the font rule to any other CSS style.
6. Apply the rule to text in your web page.
If you use the entire h1 rule provided by Google, any text formatted with the <h1> tag displays in that font. If you create a new class or ID style with the font as part of the rule, you apply the style to your text for the font to appear, just as you would have to apply any other style.
Combining style rules
There are many ways to define rules using embedded fonts in your web pages and many ways to combine style rules to create more efficient CSS. In the Jelly Rancher site, we created a style that defined the font, color, padding, and text shadow for all our headlines at once, like this:
h1, h2, h3, h4 {
text-shadow: .01em .01em .3em #333;
font-family: ‘GoodDogRegular’, sans-serif;
padding: .3em;
color: #F6FFFC;
font-size: 1.5em;
}
We then created additional styles to specify the size of the headlines differently, like this:
h1 { font-size: 3em; }
h2 { font-size: 2.5em; }
h3 { font-size: 2em; }
Polishing Design Elements with CSS 3
Until the advent of CSS 3, many common design elements, including gradients, rounded corners, and drop shadows, could only be created on a web page by using image files. Now, you can create popular design elements, such as rounded corners, with just a touch of code, as you see in the sections that follow.
Softening the edges of a box with rounded corners
If you created a box with rounded edges using previous versions of CSS, images and HTML tables, we probably don’t have to tell you what a pain it was, or how you had to create four images (one for each corner), and how you had to carefully adjust everything so that the corners lined up just so.
Whether or not you tried the old technique, you’re sure to appreciate how much easier it is when you use the CSS 3 property border-radius.
When you use the border radius style, you specify the length of the radius as the value to create the rounded edges. You can then make your rounded corners as rounded as you like, and you can apply the style to any or all of the corners of a box. In Figure 6-4 you see a diagram designed to help you see what we mean by the radius of a box and how changing the radius changes the curved edge.
Figure 6-4: The radius of the rounded corner.
You can apply this border radius style rule to any box object, such as a <div> tag or an <h1> tag. Here’s the syntax for creating rounded corners in CSS 3 for WebKit browsers (note: r stands for radius, the distance from the center of a circle to the curved edge):
-webkit-border-radius: r length;
If you want to specify a different radius for each corner, your style might look more like the following bit of code. In Figure 6-5, you see how the values change if the rounded corner is only applied to the upper right and lower left corners:
-webkit-border-top-left-radius: 0;
-webkit-border-top-right-radius: 25px;
-webkit-border-bottom-right-radius: 0;
-webkit-border-bottom-left-radius: 25px;
You can have even more control over the radius if you specify two values for the radius, like this:
-webkit-border-radius: 50px 100px;
When we designed the Jelly Rancher site, we added one font height of rounding to the box so that it remains in scale with our text, as shown in Figure 6-6. By using the em unit as our unit of measure, we can keep the design in scale on both the iPhone and iPad. This is a helpful practice when you want to add rounded corners around a text element, such as a headline:
-webkit-border-radius: 1em;
In the example shown in Figure 6-6, we’ve also used a drop shadow and a gradient. We show you how to create gradients in the section that follows. We describe how to add drop shadows with CSS 3 later in this chapter.
Creating gradients
Gradients are a favorite effect of graphic designers everywhere because they create a smooth transition of color. Adding gradients to the background of a web page or to sections within a page adds richness and depth to a design. In Figure 6-7, you can see the difference between a radial and a linear gradient.
In previous versions of CSS, if you wanted to use a gradient in the background of an element, such as a <div> tag, you had to use an image. If you were clever, you created a 1-pixel-wide graphic that was as tall as you wanted the gradient and then inserted it as a background so that it repeated to fill the space. If you designed a background image well, the image file size could be small but the limitations many. For example, you had to make the gradient as tall or taller than the space you wanted to fill, which limited your ability to create flexible page designs. Similarly, matching a second background image behind the gradient, if a design had such an image, was no simple task. In short, adding gradients to page designs was possible, but also a real hassle.
Enter CSS 3 and designers everywhere can celebrate the new gradient options to solve all those old problems at once. Gradients generated with CSS 3 will always have less impact on the download time of your pages, and they automatically adjust to fill the space perfectly. CSS 3 gradients can be designed as linear, or radial, and you can apply different bands of color at different spacing along the continuum. All in all, CSS 3 gradients can be used in most situations where a designer would want to use one and are a significant improvement to CSS.
When you add a gradient to a background — whether it’s the background of the entire page or an element within a page, such as a <div> tag — the gradient automatically adjusts to fill the entire space unless you specify a size. Gradients can also be used in the border of elements and to fill the center of a bullet in an unordered list.
Here’s the simplest syntax for creating a linear gradient in CSS 3 for webkit browsers:
-webkit-gradient( linear, <point1>, <point2>, from(<color>), to(<color>) );
Radial Gradients are created this way:
-webkit-gradient( radial, <point>, <radius>, <point>, <radius>[, <stop>]* ) <color>;
Here are two examples of gradients used as a background image:
* The following code creates a linear gradient with two colors:
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0.32, #FFFFFF),
color-stop(0.66, #245FAB)
);
* This example code creates a radial gradient with multiple colors:
background: -webkit-radial-gradient( radial, center center, 0, center center, 70.5, from(green), to(yellow));
Here’s the code we used to create the gradient in the background areas of the body, headings and asides in the Jelly Rancher web site, as shown earlier in this chapter, in Figure 6-1.
body { background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, blue),color-stop(.25, #98fc45),color-stop(1, transparent)); }
In our example, you can see that we create a linear gradient that starts at the top and moves to the bottom. You can vary the gradient by starting it at the upper left corner and ending at the lower right corner, which would form the gradient along a diagonal path. We also show several color stops in the example, each of which represents a color along the gradient. The gradient example progresses as follows:
* Start with the color blue (color-stop(0, blue)).
* Change into the hexadecimal color #98fc45 at 25% (color-stop(.25, #98fc45)).
* Then #98fc45 becomes transparent through the rest of the gradient until the background is completely transparent (color-stop (1, transparent)).
Designing with transparency
In addition to the keyword transparent, CSS 3 has another way to produce transparent or translucent elements, as shown in the following chunk of code. CSS 3 introduces the new color selector RGBa, which we introduce you to in the section “Adding drop shadows to text,” earlier in this chapter. RGBa is the same as the original RGB color selector, except that it takes a value that describes the alpha, or transparency, of the styled element.
<div style=”background: rgba(0, 0, 255, 0.2);”></div>
<div style=”background: rgba(0, 0, 255, 0.4);”></div>
<div style=”background: rgba(0, 0, 255, 0.6);”></div>
<div style=”background: rgba(0, 0, 255, 0.8);”></div>
<div style=”background: rgba(0, 0, 255, 1) ;”></div>
These elements are all blue, but they have a different amount of transparency, as illustrated in Figure 6-8. Note how the solid red block shows through. In the JellyRancher site we used gradients with transparency to let the background show through. In Figure 6-9 you can see we used it to create a layered effect. If we change the bottom most color of the page, all the layered colors let the change filter through a tint. The result is that the whole site could change with a single change of the background.
Adding drop shadows to box elements
In addition to text shadows, CSS 3 gives you the power to add shadows to box elements, such as <div> tags. In Figure 6-9, you see how we used drop shadows to set off sections, such as the aside, in this page of the Jelly Rancher site
Much like the text shadow covered earlier in this chapter (see the earlier section “Adding drop shadows to text”), the first value tells the Safari browser the horizontal offset, the second represents the vertical offset, and the third value describes how blurred the shadow should be. Again, the default is 0, and if you don’t specify the blur, the shadow’s color is completely solid.
Here’s the syntax for box drop shadows for WebKit browsers:
-webkit-box-shadow: horizontal vertical blur color;
An RGBa color gives you greater control over the shadow’s appearance because you can add transparency. Similarly, using the em measurement creates a shadow that adjusts better if the size of the text changes.
The following style adds a drop shadow to all <div> box elements on a page:
div { -webkit-box-shadow: .15em .25em .5em rgba(27, 27, 27, .6);}
Using Media Queries to Target Devices
When you design web pages with CSS, you can create one style sheet that’s used no matter which device a page is displayed on, or you can create multiple style collections designed specifically for each device. CSS 3 adds the ability to use a media query to target your style sheets based on the screen resolution, aspect ratio, and other distinguishing factors of a device. These additional options are especially useful when you’re designing for the iPhone and iPad.
In Chapter 5, we introduced this concept as we covered the HTML Framework. In this section, we get more specific about the many ways you can create, target, and associate styles with your content. Refer to Figure 6-1 to see how we’ve used media queries to alter the design of the page about oceanographer Mark Loos based on the orientation of the iPad, displaying a wider design when the iPad is in landscape mode than when it’s in portrait mode.
The ability to target devices in CSS makes it possible to use different style sheets for different types of displays: desktop and laptop monitors, iPad-size screens, or iPhone-size screens. If you don’t use media queries to target your CSS, the iPhone and iPad automatically adjust your designs for you, shrinking or enlarging the page to best fit the screen.
If you truly care about designing for optimum display on the iPhone and iPad, finding out how to use media queries to target your style sheets to each device is a helpful strategy.
Media queries build on capabilities that CSS 2 offers: the ability to target style sheets based on media type. Media types enable you to use one style sheet to control how a page appears on a computer monitor, for example, and a second one to change the appearance of that same page when it’s sent to a printer. For example, in a print-specific style sheet, you might remove a busy background image or change the text color to give it more contrast on a white sheet of paper.
When you use a media query in CSS 3, you can factor in more values than you can with just media type. These additional values include screen resolution and aspect ratio, and determine whether a device displays color — values that are especially useful when you’re designing for the iPhone and iPad, as you can see in Figures 6-1 and 6-10.
Specifying media types and features
A media query is made up of a media type, such as screen or print (the two most common), and an optional expression that checks for particular features, such as the height or width.
Here the media types supported n the iOS:
* all: Suitable for all devices
* print: Designed for print preview and for display when a page is printed
* screen: For content displayed on any screen
Remember: Don’t be confused by the Handheld media type, which is best for very limited cell phones and other devices with small screens, limited bandwidth, and monochrome displays that support only bitmapped graphics. iOS devices are categorized as screen media types.
You can combine media types with the media features described in Table 6-1.
Note: If the media type doesn’t support the feature, it has no effect.
Table 6-1 Media Features in CSS 3
Media Feature | Options |
Width | min-width, max-width |
Height | min-height, max-height |
device-width | min-device-width, max-device-width |
device-height | min-device-height, max-device-height |
aspect-ratio | min-aspect-ratio, max-aspect-ratio |
device-aspect-ratio | min-device-aspect-ratio, max-device-aspect-ratio |
Color | min-color, max-color |
color-index | min-color-index, max-color-index |
Monochrome | min-monochrome, max-monochrome |
Resolution | min-resolution, max-resolution |
Scan | Grid |
Applying styles to your page designs
You can apply style sheets by linking them, importing them, or embedding them as internal styles into the head region of your page’s HTML. You can even target devices using inline styles — a handy option if you want to apply a specific rule only to certain devices (see the example in the “Creating inline style rules” section that follows).
You can use a combination of these options, and you can import, or link, multiple external style sheets to the same Web page. you’ve defined the media type with the media features you want to target, you specify how the styles should be applied to the page using one of the following options:
Targeting devices when linking external style sheets
The most common (and generally most recommended) option is to link external CSS style sheets to each HTML page. The code for the CSS and HTML are saved in separate files, and the <link> tag connects the two.
You can link multiple style sheets to one HTML page. For example, you can create one style sheet for styles that format text and another for layout styles. You can also create external style sheets for different purposes, such as one for print and one for screen display. One of the biggest advantages of external style sheets is that they make it faster and easier to create new pages, and they make it possible to update styles across many pages at once. Note: You can attach more than one external style sheet to the same Web page.
Include the <link> tag within the <head> and close </head> tags at the top of the HTML code of a web page. The following example includes two style sheets — one designed for a computer screen and the other designed for print:
<link rel=”stylesheet” type=”text/css” media=”screen” href=”screenstyles.css”>
<link rel=”stylesheet” type=”text/css” media=”print” href=”printer.css”>
You can use a similar technique to target iPhone and iPad devices. Thus, in addition to (or instead of) the two previous style sheets for print and screen, you can link to style sheets that target the iPhone and iPad. This example links four separate style sheets to a web page, each designed for optimal display in the iPhone or iPad in landscape and portrait modes.
The comment tags are optional. When you comment code in HTML, you use these tags:
<!– comment here –!>
We include comment tags only to make the code easier for humans to read.
<!–iPad portrait –>
<link href=”css/ipadportrait.css” rel=”stylesheet” media=”only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait)”>
<!–iPad landscape –>
<link href=”css/ipadlandscape.css” rel=”stylesheet” media=”only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape)”>
<!–iPhone portrait –>
<link href=”css/iphoneportrait.css” rel=”stylesheet” media=”only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: portrait)”>
<!–iPhone landscape –>
<link href=”css/iphonelandscape.css” rel=”stylesheet” media=”only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: landscape)”>
Using imported style sheets
The ability to import style sheets, using the CSS rule @import, is similar to the HTML tag used to link style sheets to a document. You can use either of these options to apply the styles in an external style sheet to a web page, but the @import option is best used to organize multiple style sheets into one file.
The web browsers available on older mobile devices, such as low-end cell phones, do not support the @import rule with multiple style sheets.
When you’re working with many style sheets in one web site, you can combine them into one by importing them into a single file. To do so, you first create a new style sheet file (with the .css extension), and then you can import other external style sheets into that style sheet using the @import rule.
With multiple styles imported into one style sheet file you can then link to just that one style sheet from each html file. If you’re working with multiple style sheets that need to be linked to multiple HTML file, this technique can be more efficient. Combining style sheets can help you keep things better organized and means that if you add or remove a style sheet later, you only need to change the reference once to update all of the HTML documents that rely on the styles.
Here’s an example of how you can use the @import rule to link multiple style sheets to one document:<style type=”text/css” MEDIA=”screen, projection”>
@import url(/stylesheets/main.css);
@import url(/stylesheets/iPhone.css);
@import url(/stylesheets/iPad.css);
</style>
The @import option is a CSS construct. When you link a style sheet to an HTML file, you use the HTML link tag (shown in the previous section). If you use this option, the @import rule must be listed first in the document.
Using internal styles
The difference between internal and external style sheets is that with internal styles, the CSS code is stored in the <head> area at the top of the HTML page, not in a separate file that is linked or imported into the document. The styles in an internal style sheet can only apply to contents of that page.
As a general rules, external style sheets offer the greatest efficiency because they can be applied to any or all of the pages in a web site, but if you’re creating styles that will be used only on one page, an internal style can make it easier to keep track of styles applied to specific pages. This technique can also save a little download time because the browser does not need to download more than one file to apply a style to an HTML file.
Creating inline style rules
Inline styles can only apply to one element and they are applied to an html document at the place where the style is used. Of all of the CSS options, inline styles are the least common on the web because they offer none of the new efficiencies of CSS, such as the ability to make global updates and reuse style rules throughout a site.
Inline styles do offer one advantage that can come in handy on occasion, especially if you want to override other styles that are used throughout a site. For example, if you want to create a special style that makes your featured content red, you might create an inline style that changes the text color because you only want to apply that style where the featured text appears on the page.
Inline style rules can be assigned using the @media element. Here’s an example of two styles that change the display of the <h1> tag only on the iPhone causing text in the <h1> tag to display in a larger size with more line spacing when the iPhone is in landscape mode and in a smaller size when the iPhone is in portrait mode.
We include /* Portrait */ and /* Landscape */ as comments in the following code to help make it easier to read. Note that in HTML code, the comment tags are created using <!– –!>. In CSS, you use the /* */ commenting tags look like this:
/* Comments inside these tags won’t display or effect the styles. */
<style type=”text/css”>
/* Portrait */
@media screen and (max-width: 320px)
{
h1 { font-size: 1.2em; line-height: 1.2em; }
}
/* Landscape */
@media screen and (min-width: 321px)
{
h1 { font-size: 1.4em; line-height: 1.4em; }
}
</style>
Janine: Do you use a different way of commenting in the following code for a reason? If so, I suggest adding a sentence to this chapter to clarify. (You use the <!–> notation earlier in the chapter.) Thanks, Becky done, and done, tx, jw
Positioning elements for optimal display
In the Jelly Rancher site, we used the ability to target CSS to specific devices to change the design in a number of ways. The Jellyfish Tales page is a good example. In this design, shown in Figure 6-10, we alter the positioning of the three thumbnail images based on the orientation of the device.
In portrait mode, we want the images to appear at the top of the page so that they don’t get lost on smaller screens. In landscape mode, we want them to display on the right side of the page, to better take advantage of the horizontal display area. In Figure 6-10, you can see how these two style sheets cause the same HTML page to display differently based on the orientation of the iPhone.
The following bit of code makes these different displays possible.
@media screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: portrait) {
/* iPhone portrait targeted */
aside {
display: table-row;
float: left;
width: 90%;
}
@media screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: landscape) {
/* iPhone landscape targeted */
aside {
float: right;
display: table-column;
width: 100px;
}
Note that the three thumbnail images are contained in the HTML5 semantic element aside and that we’ve used the display attribute, table-row. The table-row and table-column attributes orient the block element so that it acts like part of a table. The float rule moves the element to the top of the screen, somewhat counter intuitively, by setting the float to the left, which aligns the row to the top of the page. In landscape mode, floating the display to the right causes the row of images to change position to the right-side of the screen.
To create a framework in HTML that can be altered two create two designs like this with CSS, we used an attribute of the CSS rule display, which makes the three images line up in the page as if they are in a table. This may seem counter to current standards at first, because the HTML <table> tag is no longer recommended for this kind of design. Today, the HTML <table> tag is recommended only for formatting tabular data, such as the content you might find in an excel spreadsheet. (You can learn more about the HTML <table> tag in Chapter 4, but in the following example, we’re not using the Table tag, we’re using an attribute of a the display style rule that makes content appear as it would if it were contained in a Table.)
Figure 6-10: The position of the three thumbnail images in this page changes based on the orientation of the iPhone.
Hiding Elements You Don’t Want to Display
With more space on the iPad than on the iPhone, you may find it best to hide certain elements in your designs when you display a page on the smaller screen.
Hiding the contents of a <div> tag or another element is relatively easy with CSS 3, but it doesn’t prevent the content from being downloaded to the device: Your content fits the space better, but you’re still making your site visitors download everything. This solution works well for hiding a few small items, but if you want to take this strategy a step further, in Chapter 7 you can find instructions for using PHP to remove the content from the page on the server before it’s downloaded.
The simpler, less technical solution is to use CSS to hide the element: You do that by simply creating a style with the rule display: none.
We used this trick to shorten the subhead of the Jelly Rancher site. On the iPad, we used the longer version: Specializing in Jellyfish Aquariums. On the smaller iPhone screen, we shortened it to simply Jellyfish Aquariums. In Figure 6-11, you can see the difference and how this change makes the design fit better on each device.
Figure 6-11: You can use CSS to hide elements, a great trick for doing tasks such as shortening the subhead of this jellyfish site on the iPhone.
To make it easy to isolate and hide the subhead on the iPhone, we wrapped a <span> tag around the part we don’t want to display. We used the <span> tag because it is an in-line element, not a block element and doesn’t force a line break in the middle of the subhead when it displays in its full version on the iPad.
Here’s the HTML code we used:
<header> <a href=”index.html”>
<h1>Jelly Rancher</h1>
<h2><span>Specializing in<br>
</span> Jellyfish Aquariums</h2>
</a> </header>
And, here’s the style that hides only the contents of the <span> tag:
body div h2 span, details {
display: none;
}
Conquering the Cascade
One of the most frustrating aspects of working with CSS is that sometimes styles conflict. You can define a new style and apply it to an element, for example, and then find that the style has no effect or that it changes the element in ways you didn’t expect. You can overcome this challenge in web design by understanding how the cascade effect works in Cascading Style Sheets. The cascade refers to the way that one style’s rules spill down the page like water, building one on top of another.
In the early days of HTML, web designers placed style information close to the elements they styled using attributes such as font color. If you wanted to turn your text yellow, for example, you simply surrounded it with a font tag with the color attribute set to yellow, like this: <font color=”yellow”>. With the style inline with the text, the cause and effect were easy to see, and conflicts were rare.
Separating content from style with CSS has made tracking the hierarchy of styles harder to do because each element on a page may be affected by multiple style rules. The way the cascade works in CSS makes this process even more complex. Following the cascade of rules through several rule definitions is hard, especially when all the new CSS 3 options are added.
Figure 6-12 provides a quick reference for resolving style conflicts. It ignores many of the more complex cascading rules, but simply understanding these rules will help you resolve most conflicts by helping you quickly determine which of your style rules has priority. A style rule with higher priority wins over an identical style rule with a lower priority.
The hierarchy of styles works as follows:
* Origin of the rule: To determine which CSS value is applied, the first distinction is the origin of the rule. As authors, our CSS has a higher priority than the default values of the browser or any user stylesheet. (Remember that your users, as well as your users’ browsers, may have styles that affect your pages). Note: The keyword !important can override all the others and be challenged only by another instance of !important.
* Specificity of the selector: Rules are next evaluated by the specificity of the selector, defined by giving each contradicting rule a 3-digit number specifying the value according to these rules:
* The number of ID attributes in the selector
* The number of attributes and pseudo-classes in the selector
* The number of element names in the selector
Whichever rule has a higher value wins. Here’s an example:
body#home div:first-of-type { color:red; }
body#home { color:green; }
body div:first-of-type { color:blue; }
The first rule receives a score of 1-1-2 (1 ID, 1 pseudo-class, 2 elements). The second rule gets a score of 1-0-1 (1 ID, 0 pseudo-classes, 1 element). The final rule receives a score of 0-1-2 (0 IDs, 1 pseudo-class, 2 elements).
Based on these rules, you might deduce that the text of the first <div> tag in the body of the page identified as home will be red (and you’d be right). Any other text on the page would be green. And, the text of the first <div> tag on a page that doesn’t have a body ID of home would be blue.
* Order on the page: Finally, the rules are sorted by the order in which they’re presented in the page. Consider it the tiebreaker. After all other rules are considered, the first rule to appear in a style sheet wins.
Many browsers now have built in testing tools, or addons you can install, that show you what CSS rules apply to each element in a web page. These tools, (we recommend the popular Firebug addon), make testing CSS a lot easier. You can download Firebug (for free) at www.getfirebug.com.
Chapter 7: Animating and adding Interactivity
In This Chapter
* Creating interactive features with CSS 3
* Using transitions, transformations, and animations
* Improving user experience with scripts
Much like the first layer in a birthday cake, you build the foundation for a well-structured site using HTML5 in Chapter 5. You style the site with CSS 3 in Chapter 6, adding the second layer to the cake. Now you’re ready to add the icing and decorations — the best part — adding more advanced CSS 3 features, and extending the capabilities with JavaScript.
JavaScript is a relatively simple programming language that runs within a Web browser. Using JavaScript, you can enhance CSS 3 features, add interactive messages, and even create complex games and web applications.
In this chapter, we explore how to create transformations, transitions, and animations with CSS 3. Using these exciting features, you can change the positioning of elements on a web page, and even create animated effects previously only possible with a program like Adobe Flash or by using programming that is far more complex than CSS3.
We can’t cover all of the cool new CSS 3 features in this book, and we certainly can’t teach you everything there is to know about Javascript, but you’ll find an introduction to the most exciting new features, and tips and resources for adding scripts more easily using frameworks, such as JQuery.
Creating Interactive Features CSS 3
If your goal is to convey information creatively, one of the best options for adding animation and other interactive features to a Web site today is to use CSS3.
We love Adobe Flash, and we understand why it has been a popular tool for creating animations for the web. However, today we recommend you avoid it, especially if you’re designing for the iPhone or iPad, which don’t support Flash at all. In Figure 7-1, you see the Groonies iPad game, which looks like many of the game apps you might download from the iTunes App Store. In the Groonies game you can roll the dice, move players along the virtual board, and flip cards, such as the one shown open in Figure 7-1. All this was created at http://themanyfacesof.com/the-goonies/, using CSS 3 (and a little JavaScript). (See the sidebar, “Replacing Flash with HTML5, CSS, and JavaScript,” for more on why we no longer recommend using Flash.)
Figure 7-1: The Groonies is a rich, interactive game created with CSS 3 and Javascript.
Remember: In this book, we focus on creating the best designs for the iPhone, iPad, and iPod touch. Remember, the features we create in this chapter with CSS 3 are designed for WebKit browsers. These features aren’t designed to work in other browsers, including Firefox and Internet Explorer. See the sidebar, “Making CSS animations work in other Web browsers,” later in this chapter to find out more about creating CSS 3 features that work in other browsers.
The animations and other features in this chapter work in most popular browsers that use WebKit, including Safari (on Mac, Windows, and iOS for iPad/iPhone/iPad), Chrome (on Mac, Windows, and devices that run Google’s Android operating system). We introduce how to design for WebKit browsers in Chapter 4. To learn more about the latest features supported by WebKit browsers, visit http://webkit.org/
Warning:
Making text spin around, change color, and resize just because you can do so is never a good idea. As with the infamous <blink> tag (which was overused in the early days of the Web), we recommend that you use animations sparingly in your Web pages.
Replacing Flash with HTML5, CSS, and JavaScript
Adobe Flash has been a popular video and animation tool for more than a decade. Flash makes it easy to animate images and text. The interface in the Flash development tool is set up for designers to quickly create and animate ideas that convey a deeper meaning than static images. Flash is also a great way to add fun little effects, create games, and play video. Many new forms of entertainment have been created and distributed through Flash.
Unfortunately, none of the iOS devices (including the iPhone, iPad, and iPod touch) support Flash. If your site uses Flash and someone visits your pages with one of these devices, the visitor sees nothing. Nada. Zip.
Our best advice is to recreate your Flash animations and other interactive features by using HTML5, CSS 3, and JavaScript, as we describe in this chapter. Here are a few additional advantages you get when you replace Flash content on your sites:
- You get better search engine optimization. Although Google has gotten better over the years, it still doesn’t search through Flash files for information as effectively as it does through content formatted with HTML and CSS.
- Download speeds are faster. Animations designed in Flash are generally larger than the equivalent animations designed in HTML5, CSS, and JavaScript.
- Interactive features don’t require plugins. Aninations and othe interactive features created with CSS and Javascript run in the Apple iOS without requiring a plugin, which means that they run faster and smoother.
Introducing the CSS 3 Transitions, Transformations, and Animations
CSS 3 adds many new designs features, but animation is the most exciting. Using CSS 3, you can make characters walk across the screen, boxes flip over, and images fade away. To demonstrate how animation works with CSS 3, we start by creating a simple ball that bounces in a black box, as you see in the two figures shown side by side in Figure 7-2.
Remember: We didn’t use any images to create the bouncing ball animation shown in Figure 7-2. The ball itself — and the action that makes it appear to bounce from the top of the screen to the bottom and back again — was all achieved with just a few lines of CSS 3 code.
Figure 7-2: A simple bouncing ball animation.
Before we get into the details of how we created our bouncing ball, it’s helpful to understand that CSS 3 introduces three main ways to create interactive effects and animations: transformations, transitions, and animations.
You can create many great design effects with these features, but the most interactive sites you see on the web today, such as The Groonies shown in Figure 7-1, require Javascript in addition to HTML and CSS.
Creating transformations with CSS 3
The CSS 3 transform properties enable you to transform an element to create effects in 2D and 3D. You can specify a list of transformations to change multiple aspects of an element. If multiple options are specified, each is applied in the order listed. Transformation options include the following:
* scale — Changes the height and width of an element. You can specify two numbers to define a different scale for width and height. However this element is generally used with only one number to scale an element proportionately. The first example below transforms the element to scale to half its size, the second transforms the element to half as wide and twice as tall:
-webkit-transform: scale(0.5);
-webkit-transform: scale(2, 0.5);
* translate — Use this property to translate, or move, an element from position A to position B equally along the x and y axes. You can also use translateX and translateY to move elements along only one axis at a time. For example, this code causes an element to move 150 pixels from the left and 150 from the top:
-webkit-transform: translate(150px, -150px);
* skew — Use this property to skew, or change the position of an element based on a specified value that skews an element on the x and y axes. For example, this could skews an element 20 degrees on the x axis:
-webkit-transform: skew(15deg, 4deg);
* rotate — Use this property to rotate, or change the position of an element based on a specified value that controls the angle of rotation. For example, the first example in this code rotates an element 5 degrees to the right, the second one rotates the element negative (-) 5 degrees. As you see in Figure 7-X that causes the photos on the right and left in this design to away from the center image.
-webkit-transform: rotate (5deg);
-webkit-transform: rotate (-5deg);
Tip: In the Scuba site example in Figure 7-3, notice that the two outside images rotate to the left and right, respectively, using the CSS rotate feature — but only on safari, firefox, and chrome. Hit this page with IE and the boxes are all in a straight line, but they don’t look bad that way, so there’s really no harm done.
Also notice how I’ve tucked an image into the bottom of the design so that when you turn the iPad/iPhone from landscape to portrait views there is content that fills the entire screen.
Next, I’d like to add some cool CSS 3 technique that happens when you click on one of the three photos. Can you tell we like ocean dwellers and SCUBA diving?
Figure 7-3: The right and left images in this design are angled away from the center image using the rotate property.
Making CSS 3 work in more web browsers
Both HTML5 and CSS 3 are still under development as we write this book. The CSS specification has not yet been approved by the W3C, but many browser developers have already implement parts of the working drafts of of CSS 3, including the features covered in this chapter. When browser companies implement parts of a working draft they call it experimental CSS and they usually include the browser name in the rule. That’s why there are multiple versions of the same style rules featured in this chapter.
The features covered in this chapter are designed to work in the Safari web browser. Most of them alsowork in Chrome, because both browsers are based on the webkit. For Safari and Chrome, you need to add the –webkit prefix to each style. For Firefox, you add the –moz to the beginning of each style rule. For the Opera web browser, ad –o. If you want to follow the W3C recommendations (even though they aren’t yet approved), don’t add use anything to the beginning. Here’s an example of a transition and a transformation for each of these four options:
The code for the Safari Web browser looks like this:
-webkit-transition-timing-function: linear;
-webkit-transform: scale(1.5, 2);
For Firefox, here’s what you would use to create the same transformation:
-moz-transition-timing-function: linear;
-moz-transform: scale(1.5, 2);
In the Opera Web browser:
-o-transition-timing-function: linear;
-o-transform: scale(1.5, 2);
And the current W3C recommendation is simply this:
transition-timing-function: linear;
transform: scale(1.5, 2);
Warning:
Not all browsers implement experimental rules exactly the same way. For instance here are two rules for a linear gradient:
-webkit-gradient(linear, left top, left bottom, from(#444444), to(#999999));
background-image: linear-gradient(top, #444444, #999999);
See http://developer.apple.com/devcenter/safari/ for the full list of CSS3 rules for iOS devices and see http://www.w3.org/TR/#tr_CSS for the complete list of recommended CSS3 rules from the W3C.
You find an introduction to CSS 3 and a more detailed explanation of the browser differences in Chapter 6.
Creating transitions with CSS 3
The CSS 3 transition properties make it possible to change the state of an element. Using transitions, you can do things like change an element’s color or make text fade away when someone clicks it.
Using transitions you can cause an element to enlarge when touched (or clicked), as you see on in Figure 7-4, but CSS 3 has it’s limitations. Once enlarged, there is no way to close the larger image, shown in Figure 7-4, unless you combine CSS 3 with Javascript. Writing Javascript is beyond the scope of this book, but you find some useful frameworks to make it easier to add Javascript features, such as the popular Shadobox for enlaring and reducing images, at the end of this chapter.
Figure 7-4: You can use CSS 3 to enlarge an element, such as the image on the left.
The webkit-transition includes several properties (Note: If multiple options are specified, each is applied in the order listed.):
* -webkit-transition-property — Specifies which property, such as text color, the transition affects.
* -webkit-transition-duration — Specifies the number of seconds it takes for a transition to occur. The duration can be expressed in seconds as 1s, 2s, and so on, or in milliseconds as: 500ms, 250ms, and so on.
* -webkit-transition-delay — Specifies any delay before a transition begins. , For example, you add a three-second delay by including: webkit-transition-delay: 3s.
* -webkit-transition-timing-function — Specifies the speed curve of a transition and enables you to change the speed over the duration of a transition by specifying up to five predefined values:
* ease — The default value, ease, creates a transition effect that starts slow, gets fast, and then slows again.
* linear — Creates a transition with the same speed from beginning to end.
* ease-in — Creates a transition that starts slowly.
* ease-out — Creates a transition that ends slowly.
* ease-in-out — Creates a transition that starts and ends slowly.
* cubic-bezier — This advanced option makes it possible to define your own values. Based on Bezier curve, which has been used in computer graphics since the 1960s, a cubic-bezier function uses a sequence of numeric values from 0 to 1.
Creating animations with keyframes
Much like Adobe Flash, more complex CSS 3 animations rely on keyframes. Keyframes are the points within an animation where something changes. Whenever you want to change an animated object, you need to create a new keyframe.
For instance, if we want to animate a ball bouncing, as shown in Figures 7-5, we would have a keyframe at the top of the bounce and another one at the bottom of the bounce. In this example, our ball is 50 pixels in diameter, and our container for the ball is 350 pixels tall. That means that our first keyframe places the ball at the bottom of the container, and the last one places it at the top of the container.
Here’s the code that makes this work:
@-webkit-keyframes bounce {
from { margin: 300px auto 0;}
to { margin: 0 auto 0;}
}
An @-webkit-keyframes block contains rules that define each keyframe. A keyframe defines the style for that moment within the animation. You can have a start and an end as in the example shown here, or you can define any number of points in-between. Some web browsers apply this style more smoothly than others, but Safari on the iPhone and iPad make this work quite well.
In this simple bouncing ball example, we define an animation called bounce to have two keyframes: one for the start of the animation (the from block) and one for the end (the to block). These two keyframes move our ball from the bottom to the top.
When you define an animation with a set of keyframes, you can use the following webkit-animation properties:
* animation-name — This property defines the animation used. We point it to bounce, the keyframe set we define a bit earlier. If the name is not found (missing or misspelled), the browser assumes the default value of none, and no animation is produced.
-webkit-animation-name: bounce;
* animation-duration — This property defines the length of the animation. The time value format is a number followed by a time unit identifier. The time unit identifiers are ms for milliseconds and s for seconds (1000 ms, 1s). The animation of our bouncing ball lasts one second. Figure 7-2 illustrates how the browser automatically creates the tweened frames, the frames between the top and bottom. You define the start and end and the browser fills in what’s in-between.
webkit-animation-duration: 1s;
Figure 7-5: Our bouncing ball with portions of seconds demarked.
* animation-iteration-count — This property defines the number of times an animation cycle is played. The default value is 1, and that value makes the animation play from start to end once. A value of infinite causes the animation to repeat forever. As you might guess based on that information, in the following example the animation plays 10 times:
-webkit-animation-iteration-count: 10;
* animation-direction — This property defines whether the animation should play in reverse every other cycle. If alternate is specified, every other animation cycle is played in the reverse direction. When an animation is played in reverse, the timing functions are also reversed. This is why we need to define our ball as only bouncing up. The alternate animation is played in reverse, bringing our ball back down to the bottom of our box (not unlike gravity).
-webkit-animation-direction: alternate;
Put it all together, and the style rule that makes our bouncing ball animation work looks like this:
#animationDemo #ball {
-webkit-animation-name: bounce;
-webkit-animation-duration: 1s;
-webkit-animation-iteration-count: 10;
-webkit-animation-direction: alternate;
}
When you enter one or more properties, make sure to follow this order:
1. transition-property
2. transition-duration
3. transition-timing-function
4. transition-delay
Here’s the statement we use for our ball bouncing demonstration:
#animationDemo #ball { bounce 1s 10 alternate;}
For a complete list of CSS properties that you can animate by using transitions, visit http://www.w3.org/TR/css3-transitions/#animatable-properties-.
Improving User Experience with Scripts
HTML5 and CSS 3 make it possible to add many types of animations and design elements to your pages, but for the most advanced interactive features on the web, you’ll need to use a little JavaScript, PHP, or other type of programming.
In this chapter, we try to give you all the information you need to complete the tasks we cover, but if you’re completely new to programming or want to find out more than we can cover in this book, we recommend the JavaScript introduction at the W3 School site at www.w3schools.com/js/js_intro.asp. You don’t have to know much JavaScript to use what we cover in this book, but the introduction provided at this link may help you apply and extend our examples for your own projects.
Saving space on the tiny iPhone screen
On the relatively small iPhone screen, every pixel is precious. That’s why one of our favorite scripts — and one we use in nearly every page we design for the iPhone — is designed to scroll the page down automatically, hiding the address bar and giving us more space for our designs.
The JavaScript that follows slides the window 60 pixel rows up. That gives us back the nearly 15% of screen real estate that the URL field takes up at the top of the browser window. When you add this JavaScript to a web page, it will automatically hides the address bar in Safari on the iPhone and the iPod touch without affecting any other browsers. This script is ignored by Firefox, Internet Explorer, and even Safari when it’s used on an iPad or a computer.
Here’s the code that makes this work. Simply add this code to bottom of any Web page, just before the </body> tag:
<script>
window.onload = function() {
setTimeout(function(){window.scrollTo(0, 1);}, 100);
}</script>
This script was published by Apple in 2007 when the first iPhone was released. The script tags tell HTML that JavaScript is coming: In HTML5, JavaScript is the default scripting language, so you don’t need to have anything in that tag but script. Here’s how it works:
1. The first line, window.onload = function() {, tells the browser to run this script when the page first loads.
2. The second line, setTimeout, waits a tenth of a second (defined by the 100 at the end of that line).
3. After the tenth of a second, function(){window.scrollTo(0, 1);} executes and scrolls the window to the x coordinate 0 and the y coordinate y, better known as the top of the page.
Using Frameworks to Add Advanced Features with Scripts
If HTML 5 and CSS 3 are not enough for you and you want to add more advanced features with scripts, you can save a lot of time and trouble by starting with one of the popular Javascript Frameworks, such as JQuery.
Here are some of our favorite frameworks and how they can help you add rich features to your iPhone and iPad web designs:
jQuery Mobile
This is the mobile version of the very powerful jQuery JavaScript library. The mobile version works across most smart phones and offers user interface components that go far beyond a JavaScript library. User interface elements include enhanced styled forms (as shown in Figure 7-6), a large variety of list types, searching, page transitions, themes, and more.
With the support of device manufacturers and the .mobi group, this project has the most sponsors of any of the mobile frameworks. This typically indicates the lasting power and quality of an open source project, making jQuery mobile a good bet for using now and into the future. Similar to most mobile frameworks, as we write this book, this framework is still in development.
Figure 7-6: The jQuery Mobile makes it easier to create Web App elements, such as forms.
Sencha
Sencha is a commercial framework development company, which means that once their tools are out of the beta development phase, they will probably cost money to use. That also means these tools will likely serve you better if you need a commercial-level product, and that they will come with customer support.
Reviewing the features and demos on the Sencha Web site, it’s clear this company is developing tools that can be used to create rich-media advertising, as well as complicated interactive features, such as the solitaire game, as shown in Figure 7-7.
Figure 7-7: Sencha creates commercial development tools and frameworks that can be used to create games.
IUI
http://code.google.com/p/iui/wiki/Introduction
IUI is the oldest iPhone WebApp framework. It was created by developer Joe Hewitt. The user interface offered by IUI looks very much like an iPhone application. One great feature is that this tool builds in Offline Storage (you find more information about Offline Storage at the end of this chapter). Offline Storage is what makes it possible for a Web App to work even when a user is not connected to the Internet.
iWebKit
One of the first WebApp frameworks, iWebKit (see Figure 7-8), focuses on achieving a user interface that is as close to the iOS native user interface possible using HTML5, CSS 3, and JavaScript. This framework includes helpful widgets, forms, and the ability to display RSS feeds, making it a great place to start if you want to focus only on creating Web Apps for iOS devices.
Figure 7-8: The iWebKit tool is designed to help you create designs that look a lot like native apps on the iPhone.
Impact
The Impact Engine is a framework that focuses on enabling developers to create games that feel like installed native apps. It’s a great choice if you are interested in making games using HTML5, CSS 3, and JavaScript. Current price: $99.
Cubiq.org
Sometimes you just want to keep things simple. Cubiq, created by Matteo Spinelli, a web designer and developer in Florence, Italy, is a great way to add interactive features without delving into all of the complexities of the framework tools listed earlier in this section. Spinelli has created several projects that make it super easy to add specific features to your site, including:
* iScroll: Created because of the difficulty of using position:absolute within the virtual iPhone window, iScroll makes it easier to have a fixed bar at the top or bottom of the page.
* Hardware Accelerated Accordion: An accordion shows the header or first line of a section. When the user touches it, it expands so the user can see the rest of the text in that section. These are very useful when screen real estate is scarce like it is on the iPhone or iPod Touch. Accordion effects on mobile are difficult, and usually choppy and jerky, not smooth. Matteo uses the CSS 3 translate property to better control opening and closing. It’s a smart technique because the iPhone uses hardware acceleration with this property to ensure that the transform is smooth.
* Slide-in menu: If you would like to tuck your navigation up past the top of your page, and enable users to pull it down when they need it (as shown in Figure 7-9), this one’s for you. Once added to your site it can be styled and set up to hold your navigation using any icons or design you prefer.
Figure 7-9: Visit http://cubiq.org to get everything you need to create your own slide-in menu like this one.
* Add to Home Screen: Spinelli’s Add to Homescreen feature is a script that adds a floating balloon at the bottom of your Web page on an iPhone and the top of the page on an iPad to call attention to the Add to Home Screen feature on the iPhone. The message, as shown in Figure 7-10, dynamically stays in place at the bottom of the page when the user scrolls. Matteo included the ability to customize the length of time before the message appears and disappears. It’s also available in 13 languages as of this writing.
The user can choose to Add Bookmark, Add to Home Screen, Mail Link to this Page, or Print. If the user selects Add to Home Screen, a small icon is saved on the iPhone’s Home screen. You find instructions for creating a custom icon for your site in Chapter 5. If you want to add a message to your site that encourages your visitors to complete this action, consider using the Add to Homescreen feature from Matteo Spinelli’s www.cubiq.org Web site (covered in more detail in the previous section).