Qt 4.8: QtWebKit Guide - Level 3 CSS

Qt Reference Documentation

# QtWebKit Guide - Level 3 CSS

## Level 3 CSS

This section of the QtWebKit Guide serves as an introduction to various Level 3 CSS features supported by QtWebKit:

- The Media Queries section discusses a simple client-based technique to present different interfaces and functionality from a single source of content to different classes of mobile device.
- The Selectors section concentrates on recently introduced syntax elements that make applying formatting and gathering DOM elements more flexible.
- The Visual Effects section surveys numerous formatting properties, including new color models and advanced WebKit effects.
- Finally, the Dynamic CSS section discusses 2D transforms, transitions, and keyframe animations.

This section features links to numerous sample pages that demonstrate how various CSS3 features may be applied within a mobile interface. For best results, view these samples with a modern Webkit-based browser such as Apple Safari or Google Chrome. Resize the window in which the sample appears to roughly match the dimensions of a touch-screen mobile device.

## Media Queries

CSS media queries extend media types with more detailed capabilities. Media queries offer a simple client-side mechanism to customize interfaces comprehensively via CSS.

Media queries are especially useful when extending a body of content for presentation on mobile browsers. Prior to support for this feature, there were two basic approaches to provisioning mobile web content, both server-based:

- Mobile-specific domains. Content providers might provide a separate access points for default content at `www.website.com`, with mobile content available at `m.website.com` or `website.mobi`. There might also be an additional `touch.website.com` access point targeted for higher-end touch-screen browsers.
- Dynamic Server-based Adaptation. In this case, there is a single access point, but the server sends different content, typically depending on the User-Agent header included in all browsers' HTTP requests. This approach may leverage databases of device characteristics such as WURFL or DeviceAtlas.

This section describes how to provision CSS entirely on the mobile client.

### Media Types and Media Queries

If you only want to serve interfaces for desktop browsers and low-end mobile browsers, specify external CSS files within your HTML's `head` region using media types:

     <link media="screen" href="/path/to/desktop.css" type="text/css" rel="stylesheet"/>
     <link media="handheld" href="/path/to/mobile.css" type="text/css" rel="stylesheet"/>

The `media` attribute specifies different types of browser: `screen` for large-screen desktop browsers, and `handheld` for mobile browsers. Browsers identifying themselves as `handheld` are served the `mobile.css` file, which should specify a dramatically simplified mobile interface.

A problem arises, however, when the majority of higher-end touch browsers identify themselves as the `screen` media type, to avoid being served overly simplified content that is beneath their capabilities. The example above serves a desktop-oriented design to later-generation mobile browsers. To target a higher-end mobile design to these browsers, you need to specify additional media `queries`:

     <link media="only screen and (min-device-width: 481px)" href="/path/to/desktop.css" type="text/css" rel="stylesheet"/>
     <link media="only screen and (max-device-width: 480px)" href="/path/to/touch.css" type="text/css" rel="stylesheet"/>
     <link media="handheld" href="/path/to/mobile.css" type="text/css" rel="stylesheet"/>

The first two lines specify any `screen`-typed browser whose window is wider or narrower than 480 pixels.

Regions of content that are inappropriate for presentation within either the touch-based or lower-end mobile design can then be easily removed within the corresponding CSS files:

     .widget, .nested_nav, .sidebar, .video_ad, .related_items {
         display: none;
     }

The following example demonstrates a simple message identifying your class of browser, which appears dynamically based on CSS that is linked using media types and media query syntax:

Click on the image to view the example live in a browser or click on the following links to view the CSS files.

(Desktop CSS) (Touch-Screen CSS) (Low-end Mobile CSS)

The following example shows a skeletal interface that appears differently based on the type of browser viewing it. The image below shows how it appears when viewed on a touch-based browser, but a desktop browser renders a more elaborate three-column layout:

(Desktop CSS) (Touch-Screen CSS) (Low-end Mobile CSS)

When viewed with a desktop browser, the page displays a typical desktop-style layout: a main content column surrounded by navigation and sidebar columns, with banner headers and footers that straddle the top and bottom of the screen. When viewed with a touch-based browser, the sidebar element does not appear. The main content extends to the full width of the screen, while header and navigation elements share the top of the screen. When viewed with other mobile browsers, even the top of the screen is simplified to replace header information with a simple icon.

Note that you can also use media queries to customize interfaces for tablet devices such as the Apple iPad:

     <link rel="stylesheet" media="all and (min-device-width: 481px)
         and (max-device-width: 1024px)" href="/path/to/ipad.css"/>

### In-line Media Queries

While it's generally good practice to keep CSS for different designs within separate files, you can also consolidate them. The following example provides a default san-serif font styling for `h1` elements, then different sets of style sheets for three browser categories:

     h1 { font-family : Arial, sans-serif }
     @media screen {
         h1 { color: #00008B; }
     }
     @media only screen and (max-device-width: 480px) {
         h1 { color: #00008B; font-size: medium; }
     }
     @media handheld {
         h1 { font-size: medium; font-weight: bold }
     }

Consolidating style sheets in this manner may reduce the number of separate HTTP requests, help web designers to keep track of variations among designs, and reduce style sheet properties defined redundantly in more than one file.

### Media Queries via JavaScript

Browsers that support media queries also support APIs to test them from within JavaScript. Browsers based on QtWebKit use the `matchMedia` API. Some other browsers use a slightly different (and older) `styleMedia` API, which itself used to be called the `media` API. Each can be called from the `window` object. The following function accounts for all three cases:

     function matchesMediaQuery(query) {
         if (!!window.matchMedia)
             return window.matchMedia(query).matches;
         if (!!window.styleMedia && !!window.styleMedia.matchMedium)
             return window.styleMedia.matchMedium(query);
         if (!!window.media && window.media.matchMedium)
             return window.media.matchMedium(query);
         return false;
     }

The `query` argument corresponds to the media query string used to activate the CSS. For example, the following higher-level function tests whether the browser matches design categories provided simple labels such as `desktop`, `touch`, or `mobile`:

     function isDesign(str) {
         var design;
         if (matchesMediaQuery('only screen and (min-device-width: 481px)')) {
             design = 'desktop';
         }
         else if (matchesMediaQuery('only screen and (max-device-width: 480px)')) {
             design = 'touch';
         }
         else if (matchesMediaQuery('handheld')) {
             design = 'mobile';
         }
         return str == design;
     }

You can then use the test whenever there is a need to assign functionality for a specific design. The following gathers a series of images and assigns different panel-viewing functions for `desktop` and `touch` designs, with no functionality assigned to the lower-end `mobile` design:

     var imgs = document.querySelectorAll("img.panel");
     for ( var i = 0, len = imgs.length ; i < len ; i++ ) {
         el = imgs[i];
         if ( isDesign("desktop") ) {
             imgs[i].addEventListener("mouseover", showHoverPanel);
             imgs[i].addEventListener("mouseout", hideHoverPanel);
         }
         else if ( isDesign("touch") ) {
             imgs[i].addEventListener("click", showTouchPanel);
         }
     }

The following example uses this technique to produce a simple message, dynamically generated by JavaScript, that corresponds to the message generated by CSS:

(CSS) (JavaScript)

## Selectors

Level 3 CSS provides many useful new selectors that make it easier to apply formatting to page elements. In addition, the Selectors API makes DOM elements accessible using the same CSS expressions you use to apply formatting to them. The following show alternate ways to access elements:

     var element = document.getElementById('map');
     var element = document.querySelector('#map');

     var elements = document.getElementByClassName('active');
     var elements = document.querySelectorAll('ul > li.active');

This section provides examples of how different kinds of Level 3 selectors might be applied when formatting mobile interfaces.

### Attribute Matching

It is often useful to offer visual hints marking different kinds of link. Users might want to know the difference between a link to a page on the same website and one on an external site. Links to non-HTML file types might pose special challenges to mobile users. Alternately, mobile users might get special benefit from telephone links.

You can automate this by using the CSS attribute prefix and suffix matching selectors. The following uses `^=` to mark external HTTP links, email, SMS, and telephone links, by inserting an icon after the text of the link:

         a[href^="http://"]:after, a[href^="https://"]:after
                                  { content : url(icon/external.png); }
         a[href^="mailto:"]:after { content : url(icon/email.png); }
         a[href^="sms:"]:after    { content : url(icon/sms.png); }
         a[href^="tel:"]:after    { content : url(icon/tel.gif); }

The following uses `$=` to identify various file types by common suffixes:

         a[href$=".doc"]:after { content : url(icon/ms_word.gif) }
         a[href$=".ppt"]:after { content : url(icon/powerpoint.gif) }
         a[href$=".rss"]:after, a[href$=".xml"]:after
                               { content : url(icon/feed.gif) }
         a[href$=".pdf"]:after { content : url(icon/pdf.jpg) }
         a[href$=".xls"]:after { content : url(icon/excel.jpg) }

You can also use `*=` to freely match substrings within any attribute value. The following might distinguish links to a site's blog area based on how the URL is organized:

         a[href*="/blog/"]:after { content : url(icon/blog.jpg )}

The following example demonstrates links identified by dynamically generated icons:

(CSS)

### Form Input State

The `:checked` dynamic class allows you to style radio and checkbox inputs based on their selection state:

         input[type=radio],
         input[type=checkbox]
         { text-align : right }

         input[type=radio]:checked,
         input[type=checkbox]:checked
         { text-align : left }

This enables the following mobile-friendly interface, which converts small radio and check boxes to much more accessible toggle buttons:

(CSS)

Using the dynamic `:checked` CSS class, the `text-align` property toggles from `left` to `right` depending on whether the `input` is checked or not. Note that to display button text, dynamic classes can be chained together to form complex expressions: `input[type=radio]:checked:before`.

The example also relies on the `-webkit-appearance` property, which allows you to override the default visual presentation of specialized interface elements such as radio and checkbox inputs.

The following example provides alternate styling for radio and checkbox inputs, presenting them as tappable buttons:

(CSS)

Form elements may also be re-styled based on whether they are `:enabled` or `:disabled`. In addition, the `:focus` dynamic class allows you to style text form inputs or other editable content regions that users have currently selected for editing.

### Navigational Selectors

Elements within a page that are the target of navigation can receive distinct styling using the `:target` dynamic class. The act of navigating to an element can alter its appearance, or even determine if it is to appear at all.

The following example relies on anchor navigation to display successive rows of a table within a mobile interface:

(CSS)

While the example relies on table-related tags, they are re-styled with block formatting to confine each row of information within the screen. Each row features links to other rows, triggering their display. Other links navigate away from the table, which suppresses its display altogether. This is the main CSS driving the interface:

         .mobile > tbody > tr        { display : none  }
         .mobile > tbody > tr:target { display : block }

The same technique may be used to display or dismiss optional interface elements such as panels, simply by providing navigation links to them within the page.

### Indirect Sibling Selector

The Level 2 `+` selector allows you to style elements that immediately follow other specified elements. For example, the following refers to a paragraph that immediately follows a heading at the same level of markup:

         h1 + p { font-weight: bold }

In contrast, the Level 3 `~` indirect sibling selector allows you to style any subsequent element at the same level within the markup. The following example styles any element that follows an `h2` that is classed `pullquote`:

         h2 ~ .pullquote { font-size: 90% }

Note: Webkit-based browsers do not yet allow you to style elements dynamically via indirect sibling selectors.

### Positional Selectors

Various dynamic classes allow you to style elements depending on their position with a series of elements: either elements of the same type, or other child elements of the same parent. The following example aligns a series of icons to a grid:

(CSS)

Columns are specified with the `:nth-of-type()` selector, which accepts numeric expressions as arguments. The following selectors refer to every fourth `img` element, but offset by a specified number:

         img            { position: absolute }
         img:nth-of-type(4n-3)    { left: 2% }
         img:nth-of-type(4n-2)    { left: 27% }
         img:nth-of-type(4n-1)    { left: 52% }
         img:nth-of-type(4n-0)    { left: 77% }

Alternately, keywords `odd` and `even` correspond to `2n-1` and `2n` expressions. These are useful, for example, when styling table rows with alternating background colors.

Rows are represented as the number of the element within the series, plus a fixed number. Each selector redefines the previous selector's upper range of values:

         img:nth-of-type(n)    { top: 5% }
         img:nth-of-type(n+5)    { top: 20% }
         img:nth-of-type(n+9)    { top: 35% }
         img:nth-of-type(n+13)    { top: 50% }
         img:nth-of-type(n+17)    { top: 65% }
         img:nth-of-type(n+21)    { top: 80% }

Level 3 CSS defines the following positional selectors:

- `:first-child`, `:last-child`, and `:only-child` refer to the first or last child element within a series, or when it is the only one.
- `:first-of-type`, `:last-of-type`, and `:only-of-type` refer to the first or last specified element within a series, or when it is the only one.
- `:nth-first-child()` and `:nth-last-child()` refer to the specified child element positioned from the start or end of the series.
- `:nth-first-of-type()` and `:nth-last-of-type()` refer to the specified element positioned from the start or end of the series.
- `:nth-of-type()` refers to any series of specified elements.
- `:nth-child()` refers to any series of child elements.

### Other Selectors

Level 3 CSS specifies several other potentially useful dynamic classes that can be added to selectors:

- `:empty` refers to an element that contains no child elements, including text nodes.
- `:root` is a markup-independent way to refer to elements that are postioned at the root of the document, in most cases the `html` tag.
- The `:not()` dynamic class allows you to narrow a range of selectors. This may be more useful when gathering elements via the Selectors API. For example, the following JavaScript gathers form inputs, but not including submit buttons:

           var inputs = document.querySelectorAll("input:not([type=submit])");

## Visual Effects

QtWebKit supports numerous Level 3 CSS visual features. This section briefly demonstrates how many of these recently available visual features may be used to refine mobile web designs.

These more advanced CSS3 effects tend to be available only on the latest generation of mobile browsers. Still, it is safe to use them, even if the design degrades somewhat for devices that don't support them. When a browser encounters CSS properties or values it can't interpret, it simply ignores them. Designers can respond by providing fallback options to allow for graceful degradation. For example, the following CSS specifies a plain gray background in case the browser does not support gradients:

     background: #aaaaaa;
     background: -webkit-gradient(linear, center top, center bottom,
             from(#777777), color-stop(50%,#dddddd), to(#777777) );

Note that many of the CSS properties discussed in this section were implemented relatively recently, and vendors of browser rendering engines (such as WebKit) may still be in the process of testing and standardizing their behavior. These property names feature vendor prefixes such as `-webkit-` for WebKit, `-moz-` for Mozilla, and `-o-` for Opera.

It may be possible to extend CSS properties to these various browsers by providing vendor-specific syntax. The following example shows how to extend the `border-image` property to the Opera browser or Mozilla-based Fennec or the Maemo Browser for Nokia N900. It also shows the property's final name following the process of standardization:

     -webkit-border-image     : url(img/border-frame.gif) 10 stretch stretch;
     -moz-border-image     : url(img/border-frame.gif) 10 stretch stretch;
     -o-border-image         : url(img/border-frame.gif) 10 stretch stretch;
     border-image         : url(img/border-frame.gif) 10 stretch stretch;

In some cases, there are slight variations in the syntax each vendor expects as property values.

### Specifying Color and Opacity

Prior to CSS3, there were three options when specifying color values: named colors, hexadecimal color values, or RGB values. CSS3 provides additional ways to specify colors:

- HSL. Colors defined with the HSL model specify the hue as a radial or degree coordinate, then its saturation and luminence as percentages. The following example specifies red and green values:

           background: hsl(0  , 100%, 60%);
           background: hsl(128, 75% , 33%);

- HSLA. Same as HSL, but specifying an additional decimal alpha value that corresponds to opacity. The following specifies a fully opaque red, followed by a partial transparency:

           background: hsla(0, 100%, 60%, 1.0);
           background: hsla(0, 100%, 60%, 0.5);

- RGBA. Same as RGB, but specifying an additional decimal alpha value that corresponds to opacity. The following the same transition from opaque to transparent as shown above:

           background: rgba(100%, 0%, 0%, 1.0);
           background: rgba(100%, 0%, 0%, 0.5);

With the addition of opacity to color definitions, you can now also specify `transparent` as a color name. Note that while RGBA and HSLA options are now available, you can still use the familiar `opacity` property independently of color definitions.

### Rounded Corners

In addition to removing harsh edges, rounded corners often help distinguish active items from static background elements. Rounded corners are implemented using the `border-radius` property. The following rounds off an edge to the same extent that interior elements are offset:

         .rounded {
             border-radius    : 1em;
             padding        : 1em;
         }

The following example demonstrates how rounded corners can enhance a mobile design, by marking the start and end of large regions of content, such as a list of links:

(CSS)

The greater the measurement applied to an element's `border-radius`, the more dramatically rounded are its corners. For example, applying a `border-radius` that is half an element's overall dimensions results in a circle:

         .circle {
             width              : 4em;
             height             : 4em;
             border-radius      : 2em;
         }

You can also set each corner individually, and specify a pair of values to achieve oval-shaped borders:

         border-top-left-radius : 2em/1em;

### Border Images

Border images allow you to apply customized marquee effects, as in the following example:

(CSS)

In this case, the image stretches to fit an element's dimensions:

         -webkit-border-image : url(img/border-frame.gif) 10 stretch stretch;

As is true of the `border` property, a single numeric argument specifies the width of the border as a whole, or up to four values to modify the width of each side.

Any border image you specify substitutes some or all of an element's normal border. The `border-image` and `border-corner-image` each collectively represent four more specific properties.

For `border-image`, these properties are:

- `border-top-image`
- `border-right-image`
- `border-bottom-image`
- `border-left-image`

For `border-corner-image`, these properties are:

- `border-top-left-image`
- `border-top-right-image`
- `border-bottom-right-image`
- `border-bottom-left-image`

The `border-image` property specifies a single image for all four edge borders. The `border-corner-image` property specifies an image for all four corner borders. To specify images individually for any of the edge or corner borders, use any of the eight individual properties.

When specifying any border edge or corner image values:

- A `stretch` value stretches one image to fill the element border area, as shown in the example above.
- A `repeat` value repeats one image until it fills the element border area and clips any overflow, for example:

           -webkit-border-image : url(img/border-frame.gif) 10 repeat repeat;

  In this case the first `repeat` applies to top and bottom edge borders, and the second applies to left and right edge borders.

### Backgrounds

CSS3 allows you to specify more than one background image at a time. The following example shows an accordion-style tabbed interface:

(CSS) (JavaScript)

By default, tabs display a single icon image, but when selected feature an additional gradient background image. The following CSS shows how both icon and background can receive their own series of specifications, affecting their offset or whether each image repeats:

         background-image    : url(img/select.png)    , url(img/gradient.jpg);
         background-repeat    : no-repeat        , repeat-x;
         background-position    : 12px 12px        , 0 0;

In addition, you may set the `background-size` property to `contain` to scale images to the size of the containing element. (Level 2 CSS allowed only specific measurements or percentages of the image's size.)

### Text Shadow and Stroke

Shadows can be applied to text. As the following example shows, text shadows may interfere with the legibility of text, and are seldom appropriate unless they're used for large, sans-serif display headings:

(CSS)

In addition to the shadow's color, the property accepts two measurements to represent its offset from the text, while the third specifies the extent to which the shadow is blurred:

         h1,h2,h3,h4 { text-shadow : 0.25em 0.25em 0.25em #aaaaaa; }

CSS3 also allows you to apply a different colored fill to characters, suitable mainly for larger display type or subtle animations:

(CSS)

In the following CSS, `-webkit-text-fill-color` is synonymous with the standard `color` property:

         -webkit-text-stroke-color    : #000000;
         -webkit-text-stroke-width    : 1px;
         -webkit-text-fill-color        : purple;

### Text Overflow

Web developers are familiar with the `overflow` property, which can be used to hide content that exceeds an element's dimensions, or else to make it accessible via scrolling. CSS3 specifies an additional `text-overflow` property that allows you to add ellipses as a suffix to any text that overflows the element, to indicate the presence of additional text.

The following example shows how the `text-overflow` property allows you to present user-selectable links to expanded regions of text within a page:

(CSS) (JavaScript)

Use the `text-overflow` property in conjunction with `overflow` and `white-space`:

         text-overflow    : ellipsis;
         overflow    : hidden;
         white-space    : nowrap;

For `text-overflow` to work, the element's `white-space` must be set to `nowrap`, overriding the default `normal` value. This prevents words from wrapping onto another line as is standard behavior outside the `pre` tag, and forces text past the right edge of the element.

(The element's `text-overflow` may specify both `ellipsis` and `ellipsis-word`, the latter of which is not as widely implemented.)

### Custom Scrollbars

In general, scrollable elements should be avoided wherever possible within mobile interfaces. Drag gestures already allow users to scroll windows vertically, and narrow mobile screens are not suitable for overly wide content.

In cases where content can only be viewed within a scrolling window, scrollbars can be reformatted to make them more accessible to mobile users. The following example presents a block of code within a touch-enabled mobile interface:

(CSS)

This interface uses standard scrollbars, but their appearance is enhanced using low-level pseudo-element CSS classes that refer to individual components within the scrollbar.

Simply by invoking the following CSS selector, you disable scrollbars' default appearance:

         pre::-webkit-scrollbar { height : 3em }

In this case, the specified property increases the scrollbar's default `height` to make it easier for mobile users to tap it with their fingers.

Each additional scrollbar component must then be explicitly defined, otherwise it does not render. The following CSS provides custom styling for the horizontal panning buttons:

         ::-webkit-scrollbar-button:increment {
             background-image    : url(img/arrow_right.png);
             background-size    : contain;
             background-repeat    : no-repeat;
             width        : 3em;
             height        : 3em;
         }
         ::-webkit-scrollbar-button:decrement {
             background-image    : url(img/arrow_left.png);
             background-size    : contain;
             background-repeat    : no-repeat;
             width        : 3em;
             height        : 3em;
         }

In this case, the scrollbar region between the two navigation icons is still active, but not obviously so since its visual formatting has been overridden. The simpler set of controls is far more suitable for a mobile interface.

Webkit provides pseudo-elements for the following components:

- `scrollbar` refers to scrollbar as a whole. Additional dynamic classes can be appended to specify `:vertical` and `:horizontal` scrollbars. The `:corner-present` dynamic class activates when both scrollbars are present.
- `scrollbar-button` refers to incremental navigation buttons. Each button can be styled separately with `:increment` and `:decrement` dynamic classes.
- `scrollbar-thumb` refers to the scrollbar's slider control.
- `scrollbar-track` refers to the active navigation region between buttons.
- `scrollbar-track-piece` refers to each portion of the track on either side of the thumb control. These can be styled separately using `:start` and `:end` dynamic classes.
- `scrollbar-corner` refers to the corner where scrollbar tracks meet. The `resizer` pseudo-element also refers to this corner, but for resizable elements such as `textarea`.
- The `:double-button` and `:single-button` dynamic classes refer to whether incrementor and decrementors are paired together redundantly at each end of the track, while `:no-button` refers to whether they display at all.

See Also: Surfin' Safari: Styling Scrollbars

### Gradients

Gradients provide a graduated shading effect that can add subtle texture to background elements, and can provide buttons a three-dimensional, beveled appearance. Explicit support for gradients means there's no longer a need to implement them as repeating background images.

Specify gradients using CSS properties such as the following:

         background: #aaaaaa;
         background: -webkit-gradient(linear, center top, center bottom,
                         from(#dddddd), to(#777777) );

Note the pair of `background` statements. The first specifies a monochrome fallback color for browsers that do not support gradients.

The function specifies a simple `linear` gradient from the top to the bottom of the element, shifting from a light to a darker gray.

The following example shows how this gradient can be applied to a background element:

(CSS)

Gradients cannot be applied to the `body` element. Instead, they are here applied to an element that covers the background.

You can specify more than one gradient for the same element. The following shifts from a dark to a light gray halfway down the element, then back to dark:

         background: -webkit-gradient(linear, center top, center bottom,
                 from(#777777), color-stop(50%, #dddddd), to(#777777) );

Here is how the additional `color-stop` appears when applied to the same background element:

(CSS)

Gradients can also provide a textured, three-dimensional appearance for buttons. In the following example, the gradient is inverted and darkened when each button is pressed:

(CSS)

In addition to linear gradients, CSS3 also specifies radial gradients that emanate from a single point. The following example demonstrates a colorful radial gradient used to mark where users touch the screen:

(CSS) (JavaScript)

The syntax is slightly different than for linear gradients. The first two comma-separated arguments after the `radial` statement specify the coordinates of the inner circle, and its radius. The next two arguments specify the coordinates and radius of the outer circle:

         background: -webkit-gradient(radial, 90 120, 5, 100 130, 48,
                 from(#777777), color-stop(50%, #dddddd), to(#777777) );

The use of `from`, `to` values and `color-stop` in radial gradients are the same as for linear gradients.

### Reflections

Reflections offer a mirror-like effect which, in the following example, adds a sense of weight to headings and images:

(CSS)

The property's syntax specifies the edge of the element at which to reflect, the offset, and an overlay color. In this case, the color is a gradient, which causes the reflection to gradually fade:

         -webkit-box-reflect : below -0.25em -webkit-gradient(linear, center
                     top, center bottom, from(transparent), color-stop(0.25,
                     transparent), to(black));

### Masks

Masks offer a way to modify an image by overlaying either another image, or a gradient. The following example shows a series of thumbnail images that appear faded at their bottom edge until selected:

(CSS) (JavaScript)

The gradient's opacity shifts from `1` to `0`, an effect that translates to the image:

         -webkit-mask-box-image : -webkit-gradient(linear, left top, left
            bottom, from(rgba(0, 0, 0, 1)), to(rgba(0, 0, 0, 0)));

The following example demonstrates an image used as a mask to frame another image:

(CSS)

Separately, the component images look like these:

The syntax is the same for border images, and allows you to stretch one image over the other:

         -webkit-mask-box-image : url(img/mask.png) 5% stretch;

## Dynamic CSS

Animations help enhance touch-based mobile interfaces in many ways. They help ease transitions from one display state to another that might otherwise appear jarring. They help provide a sense of navigational orientation. They also often simulate tactile feedback as users' touches result in a tangible visual effect. Overall, they add a sense of vibrancy that increases users' engagement with the content on display.

Support by QtWebKit for HTML5 allows you to choose from among several flavors of web-based animation: Canvas, SVG, and Level 3 CSS. Web developers may also be familiar with lower-level JavaScript-based animation techniques, which form the basis of many popular JavaScript libraries such as jQuery and Prototype. This section focuses on CSS-based animations, since they are more appropriate to integrate throughout a web design, without the additional overhead JavaScript libraries require. Like Adobe Flash, SVG and Canvas offer more specialized, low-level graphics frameworks whose animation features are more appropriate for generating standalone effects.

This section demonstrates animation techniques by offering a series of examples that apply to common mobile design tasks. While some of these tasks are addressed by existing JavaScript frameworks such as jQuery and Prototype, the examples provided here illustrate some CSS-only alternatives.

### CSS Animation Concepts

Level 3 CSS introduces three distinct concepts that are relevant when crafting dynamic effects, which are discussed in the following sections:

- Transforms offer a series of manipulations to screen elements. By themselves, transforms present only static visual effects, but they become especially useful as part of dynamic transitions and animations. Simple transforms are two-dimensional, with three-dimensional transforms gaining gradual support.
- Transitions entail a graduated shift from one explicit display state to another. Transitional shifts apply to any CSS property that specifies numeric or color values.
- Animations offer more complex sequences of transitions that can specify many intermediate display states. Unlike simple transitions, animations can also be initiated more freely.

### 2D Transforms

Transforms allow you to freely displace box elements from where they would ordinarily appear. Several transform functions are available, allowing you to scale, rotate, skew, or translate (move) objects.

The `translate` function moves an element from its default location, and accepts `x` and `y` measurements as arguments. The following moves an element off the right edge of the screen:

         -webkit-transform: translate(120%, 0);

Alternately, `translateX` and `translateY` functions allow you to specify each axis independently. This moves the element off the top of the screen:

         -webkit-transform: translateX(0.0) translateY(-120%);

Scale transforms allow you enlarge or shrink an element, with the scale expressed as a decimal. By itself, `scale` modifies height and width proportionately, but the alternative `scaleX` and `scaleY` functions allow you to constrain scaling to a single axis.

The following animation demonstrates a `translate` function, which moves the element from off the screen, followed by series of `scale`, `scaleX`, and `scaleY` functions:

(CSS)

By default, transforms originate from the center of the element, but you can specify any edge using the `-webkit-transform-origin` property. The following reduces an element to 75% of its original size, while keeping it at its original bottom edge:

         -webkit-transform        : scale(0.75);
         -webkit-transform-origin    : bottom;

The following example uses this scale transform to shrink icons that are assigned to in-line links, with icons aligning to the text's baseline:

(CSS)

The `rotate` function accepts degree or radian arguments, with negative arguments specifying counter-clockwise motion. The following animation demonstrates two rotations: the first clockwise around the element's center point, and the second counter-clockwise around the top left corner:

(CSS)

The `skew` function also accepts positive or negative degree arguments, specifying the extent to which to modify the bottom left corner's 90-degree angle. The `skew` and `skewX` functions shift the element horizontally, but the alternative `skewY` function shifts the element vertically. The following animation demonstrates a `skewX` followed by a `skewY`:

(CSS)

In the following example, a variety of transforms make a set of three navigational tab icons appear to be part of a cube:

(CSS)

The example also implements the tab icons as internal links that activate display of content using the `:target` dynamic class. See the Navigational Selectors section for more information.

Note that transforms can include any combination of the functions described above:

         nav > a:nth-of-type(3) {
             background-image    : url(img/S_google.jpg);
             -webkit-transform    : rotate(-60deg) skew(-30deg) translate(1.7em, 0em);
         }

### Transitions

Transitions allow you to gradually shift from one defined CSS state to another. Any CSS property expressed as a numeric or color value (including a color name or hex value) can be transitioned between two style sheets. Properties such as `display` that have discrete sets of named values, such as the `display` property's `block` or `none` values, cannot be transitioned. In cases where named values translate internally to numeric values, such as the `border-width` property's `thin` and `thick` values, they can be transitioned.

The following example shows a series of transitions from a collapsed icon state to an expanded panel:

(CSS) (JavaScript)

Each style sheet specifies a different `max-width` value, and each accompanying transition, defined separately for each state, allows the value to shift over the course of half of a second:

         nav.expanded {
             max-width        : 95%;
             -webkit-transition    : max-width 0.5s ease-in-out;
         }
         nav.collapsed {
             max-width        : 10%;
             -webkit-transition    : max-width 0.5s ease-in-out;
         }

That shorthand syntax can be expanded to several different properties:

         nav.expanded {
             max-width                : 95%;
             -webkit-transition-property        : max-width;
             -webkit-transition-duration        : 0.5s;
             -webkit-transition-timing-function    : ease-in-out;
         }
         nav.collapsed {
             max-width                : 10%;
             -webkit-transition-property        : max-width;
             -webkit-transition-duration        : 0.5s;
             -webkit-transition-timing-function    : ease-in-out;
         }

Available transition functions include `linear`, `ease-in`, `ease-out`, `ease-in-out` and `cubic-bezier`.

Note that the `max-width` properties in both style sheets both use percentages to specify measurements. Transitions may not work properly if you shift from one unit to another.

The example above specifies an additional set of transitions affecting the icons nested within the navigation panel:

         nav.expanded > .option {
             opacity        : 1;
             -webkit-transform    : scale(1.0);
             -webkit-transition    : all 0.5s linear;
         }
         nav.collapsed > .option {
             opacity        : 0;
             -webkit-transform    : scale(0.0);
             -webkit-transition    : all 0.5s linear;
         }

The shifting `scale` transform makes icons appear to zoom in to fill the space, while `opacity` makes them fade in. Specifying `all` as the transition property applies to any valid property that differs between the two states.

These nested transitions execute at the same time as those assigned to the parent `nav` element. The combined effect appears to be a single transition.

### Transitional Sequences

The prior example showed a single transition, but transitions can also be run in sequence to form more complex animations. The following example demonstrates an embedded navigation panel that, when pressed, expands horizontally, then vertically to reveal numerous navigation options:

(CSS) (JavaScript)

The style sheets specify separate, comma-separated transitions for `width` and `height` properties:

         #accordion.expanded {
             width: 80%;
             height: 90%;
             -webkit-transition:
                 width 0.5s ease-in-out 0.0s,
                 height 0.5s ease-in-out 0.5s
             ;
         }
         #accordion.collapsed {
             width: 10%;
             height: 7%;
             -webkit-transition:
                 height 0.5s ease-in-out 0.0s,
                 width 0.5s ease-in-out 0.5s
             ;
         }

Each transition's additional time measurement specifies a delay. The long-form syntax may make this clearer:

         #accordion.expanded {
             width: 80%;
             height: 90%;
             -webkit-transition-property        : width        , height;
             -webkit-transition-duration        : 0.5s        , 0.5s;
             -webkit-transition-timing-function    : ease-in-out    , ease-in-out;
             -webkit-transition-delay        : 0.0s        , 0.5s;
         }
         #accordion.collapsed {
             width                : 10%;
             height                : 7%;
             -webkit-transition-property        : height    , width;
             -webkit-transition-duration        : 0.5s        , 0.5s;
             -webkit-transition-timing-function    : ease-in-out    , ease-in-out;
             -webkit-transition-delay        : 0.0s        , 0.5s;
         }

The shift to the `expanded` state involves two transitions, each of which lasts half a second and relies on the same `ease-in-out` function. The first takes place immediately and affects the `width` property. The second, affecting the `height` property, takes place after a delay that matches the first transition's duration. The reverse transition is much the same, only the `height` property transitions before the `width` to reverse the effect.

In addition to the navigation element's sequence of transitions, nested accordion-style animations activate when users expand top-level headings. Subheadings are revealed using a `scaleY` transform, which makes them appear as if they are flipping upwards.

The following example shows a photo gallery interface that uses the same techniques. (Size the window to emulate a smaller mobile screen.)

(CSS) (JavaScript)

The main interface uses simple transitions affecting `opacity`, along with `scale` and `translate` transforms, which combined make queued images appear dimmer, smaller, and horizontally offset from the main image.

A separate sequence of transitions activates when users tap selected images. The first transition uses a `scaleX` transform to flip the image towards the center. The second then flips out a panel featuring details on the photo. When users navigate away to adjacent photos, the panel automatically flips back to its original state as it is moved to the side.

Another example shows an interface featuring a simple list of items:

(CSS) (JavaScript)

When dismissed, items are wiped off the screen using a `skew` transform that provides the illusion of speed. Remaining items move upwards to fill the space vacated by items that have been removed.

This example uses the same technique of sequential transitions. The first transition applies to the combined `translate`/`skew` transform. The second, delayed transition modifies the `top` property to align remaining items to a grid.

Note that for items to reposition themselves in this example, a vertical grid must be explicitly specified. You can only apply transitions between properties you explicitly define and activate, not between values the browser assigns internally to automatically position elements relative to each other.

### Keyframe Animations

The previous section showed how you can chain sequences of transitions to produce complex effects. Animations also allow you to define many intermediary interface states, but using a far simpler syntax, and not assigned to transitions between CSS states.

The following example shows a simple animation of icons that pulse when selected:

(CSS)

It uses the following CSS, shown here in both abbreviated and long form:

         nav > a:target { -webkit-animation : pulse 1s infinite; }

         nav > a:target {
             -webkit-animation-name        : pulse;
             -webkit-animation-duration        : 1s;
             -webkit-animation-iteration-count    : infinite;
         }

You supply a `name` for the animation that corresponds to a `keyframes` rule defined separately within your CSS:

         @-webkit-keyframes pulse {
             0% { opacity : 1.0 }
             50% { opacity : 0.7 }
         }

Percentages mark new animation states within the course of the animation, and behave much like CSS selectors. In this case, the animation shifts between two separate states over the course of a second: opaque and slightly dimmed. With its `iteration-count` set to `infinite` rather than a set number, the animation only stops when the link is no longer selected.

The following example demonstrates a popular mobile design pattern implemented with CSS. Navigation to nested subheads appears to wipe to the right, while navigating upwards in the hierarchy appears to wipe to the left:

(CSS)

It relies on keyframes rules such as the following, which define a simple start and end state:

         @-webkit-keyframes slide_in {
           from {
             left            : 80%;
             right           : -80%;
           }
           to {
             left            : 0em;
             right           : 0em;
           }
         }

Unlike a transition, the animation is triggered immediately when the page loads, but only if the target of navigation is an anchor whose ID is `in` or `out`. If you navigate to the page itself, no animation occurs.

The following example uses a keyframe animation to scroll through banner options at the top of the screen:

(CSS)

The animation defines a set of rapid shifts alternating with long static phases. It modifies the left offset of an element that is five times the width of the window.

         @-webkit-keyframes banner_scroll {
             0% { left    : 0%; }
             18% { left    : 0%; }
             20% { left    : -100%; }
             38% { left    : -100%; }
             40% { left    : -200%; }
             58% { left    : -200%; }
             60% { left    : -300%; }
             78% { left    : -300%; }
             80% { left    : -400%; }
             95% { left    : -400%; }
             100% { left : 0%; }
         }

Finally, the demonstrations of rotate, scale, and skew 2D transforms that opened this section all rely on separate keyframe animations to slide in and manipulate a series of panels. Separate `-webkit-animation-delay` settings for each panel control the sequence of each presentation.

- QtWebKit Guide -back to the main page