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:

  1. <link media="screen" href="/path/to/desktop.css" type="text/css" rel="stylesheet"/>
  2. <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:

  1. <link media="only screen and (min-device-width: 481px)" href="/path/to/desktop.css" type="text/css" rel="stylesheet"/>
  2. <link media="only screen and (max-device-width: 480px)" href="/path/to/touch.css" type="text/css" rel="stylesheet"/>
  3. <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:

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

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:

  1. <link rel="stylesheet" media="all and (min-device-width: 481px)
  2.    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:

  1. h1  { font-family : Arial, sans-serif }
  2. @media screen  {
  3.     h1  { color: #00008B; }
  4. }
  5. @media only screen and (max-device-width: 480px)  {
  6.     h1  { color: #00008B; font-size: medium; }
  7. }
  8. @media handheld  {
  9.     h1  { font-size: medium; font-weight: bold }
  10. }

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:

  1. function matchesMediaQuery(query)  {
  2.     if (!!window.matchMedia)
  3.         return window.matchMedia(query).matches;
  4.     if (!!window.styleMedia && !!window.styleMedia.matchMedium)
  5.         return window.styleMedia.matchMedium(query);
  6.     if (!!window.media && window.media.matchMedium)
  7.         return window.media.matchMedium(query);
  8.     return false;
  9. }

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:

  1. function isDesign(str)  {
  2.     var design;
  3.     if (matchesMediaQuery('only screen and (min-device-width: 481px)'))  {
  4.         design = 'desktop';
  5.     }
  6.     else if (matchesMediaQuery('only screen and (max-device-width: 480px)'))  {
  7.         design = 'touch';
  8.     }
  9.     else if (matchesMediaQuery('handheld'))  {
  10.         design = 'mobile';
  11.     }
  12.     return str == design;
  13. }

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:

  1. var imgs = document.querySelectorAll("img.panel");
  2. for ( var i = 0, len = imgs.length ; i < len ; i++ )  {
  3.     el = imgs[i];
  4.     if ( isDesign("desktop") )  {
  5.         imgs[i].addEventListener("mouseover", showHoverPanel);
  6.         imgs[i].addEventListener("mouseout", hideHoverPanel);
  7.     }
  8.     else if ( isDesign("touch") )  {
  9.         imgs[i].addEventListener("click", showTouchPanel);
  10.     }
  11. }

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:

  1. var element = document.getElementById('map');
  2. var element = document.querySelector('#map');
  3.  
  4. var elements = document.getElementByClassName('active');
  5. 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:

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

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

  1.     a[href$=".doc"]:after  { content : url(icon/ms_word.gif) }
  2.     a[href$=".ppt"]:after  { content : url(icon/powerpoint.gif) }
  3.     a[href$=".rss"]:after, a[href$=".xml"]:after
  4.                            { content : url(icon/feed.gif) }
  5.     a[href$=".pdf"]:after  { content : url(icon/pdf.jpg) }
  6.     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:

  1.     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:

  1.     input[type=radio],
  2.     input[type=checkbox]
  3.      { text-align : right }
  4.  
  5.     input[type=radio]:checked,
  6.     input[type=checkbox]:checked
  7.      { 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:

  1.     .mobile > tbody > tr         { display : none  }
  2.     .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:

  1.     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:

  1.     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:

  1.     img             { position: absolute }
  2.     img:nth-of-type(4n-3)     { left: 2% }
  3.     img:nth-of-type(4n-2)     { left: 27% }
  4.     img:nth-of-type(4n-1)     { left: 52% }
  5.     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:

  1.     img:nth-of-type(n)     { top: 5% }
  2.     img:nth-of-type(n+5)     { top: 20% }
  3.     img:nth-of-type(n+9)     { top: 35% }
  4.     img:nth-of-type(n+13)     { top: 50% }
  5.     img:nth-of-type(n+17)     { top: 65% }
  6.     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:
    1.     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:

  1. background: #aaaaaa;
  2. background: -webkit-gradient(linear, center top, center bottom,
  3.         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:

  1. -webkit-border-image     : url(img/border-frame.gif) 10 stretch stretch;
  2. -moz-border-image     : url(img/border-frame.gif) 10 stretch stretch;
  3. -o-border-image         : url(img/border-frame.gif) 10 stretch stretch;
  4. 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:
    1.     background: hsl(0  , 100%, 60%);
    2.     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:
    1.     background: hsla(0, 100%, 60%, 1.0);
    2.     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:
    1.     background: rgba(100%, 0%, 0%, 1.0);
    2.     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:

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

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:

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

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

  1.     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:

  1.     -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:
    1.     -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:

  1.     background-image    : url(img/select.png)    , url(img/gradient.jpg);
  2.     background-repeat    : no-repeat        , repeat-x;
  3.     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:

  1.     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:

  1.     -webkit-text-stroke-color    : #000000;
  2.     -webkit-text-stroke-width    : 1px;
  3.     -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:

  1.     text-overflow    : ellipsis;
  2.     overflow    : hidden;
  3.     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:

  1.     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:

  1.     ::-webkit-scrollbar-button:increment  {
  2.         background-image    : url(img/arrow_right.png);
  3.         background-size    : contain;
  4.         background-repeat    : no-repeat;
  5.         width        : 3em;
  6.         height        : 3em;
  7.     }
  8.     ::-webkit-scrollbar-button:decrement  {
  9.         background-image    : url(img/arrow_left.png);
  10.         background-size    : contain;
  11.         background-repeat    : no-repeat;
  12.         width        : 3em;
  13.         height        : 3em;
  14.     }

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:

  1.     background: #aaaaaa;
  2.     background: -webkit-gradient(linear, center top, center bottom,
  3.                     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:

  1.     background: -webkit-gradient(linear, center top, center bottom,
  2.             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:

  1.     background: -webkit-gradient(radial, 90 120, 5, 100 130, 48,
  2.             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:

  1.     -webkit-box-reflect : below -0.25em -webkit-gradient(linear, center
  2.                 top, center bottom, from(transparent), color-stop(0.25,
  3.                 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:

  1.     -webkit-mask-box-image : -webkit-gradient(linear, left top, left
  2.        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:

  1.     -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:

  1.     -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:

  1.     -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:

  1.     -webkit-transform        : scale(0.75);
  2.     -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:

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

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:

  1.     nav.expanded  {
  2.         max-width        : 95%;
  3.         -webkit-transition    : max-width 0.5s ease-in-out;
  4.     }
  5.     nav.collapsed  {
  6.         max-width        : 10%;
  7.         -webkit-transition    : max-width 0.5s ease-in-out;
  8.     }

That shorthand syntax can be expanded to several different properties:

  1.     nav.expanded  {
  2.         max-width                : 95%;
  3.         -webkit-transition-property        : max-width;
  4.         -webkit-transition-duration        : 0.5s;
  5.         -webkit-transition-timing-function    : ease-in-out;
  6.     }
  7.     nav.collapsed  {
  8.         max-width                : 10%;
  9.         -webkit-transition-property        : max-width;
  10.         -webkit-transition-duration        : 0.5s;
  11.         -webkit-transition-timing-function    : ease-in-out;
  12.     }

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:

  1.     nav.expanded > .option  {
  2.         opacity        : 1;
  3.         -webkit-transform    : scale(1.0);
  4.         -webkit-transition    : all 0.5s linear;
  5.     }
  6.     nav.collapsed > .option  {
  7.         opacity        : 0;
  8.         -webkit-transform    : scale(0.0);
  9.         -webkit-transition    : all 0.5s linear;
  10.     }

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:

  1.     #accordion.expanded  {
  2.         width: 80%;
  3.         height: 90%;
  4.         -webkit-transition:
  5.             width 0.5s ease-in-out 0.0s,
  6.             height 0.5s ease-in-out 0.5s
  7.         ;
  8.     }
  9.     #accordion.collapsed  {
  10.         width: 10%;
  11.         height: 7%;
  12.         -webkit-transition:
  13.             height 0.5s ease-in-out 0.0s,
  14.             width 0.5s ease-in-out 0.5s
  15.         ;
  16.     }

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

  1.     #accordion.expanded  {
  2.         width: 80%;
  3.         height: 90%;
  4.         -webkit-transition-property        : width        , height;
  5.         -webkit-transition-duration        : 0.5s        , 0.5s;
  6.         -webkit-transition-timing-function    : ease-in-out    , ease-in-out;
  7.         -webkit-transition-delay        : 0.0s        , 0.5s;
  8.     }
  9.     #accordion.collapsed  {
  10.         width                : 10%;
  11.         height                : 7%;
  12.         -webkit-transition-property        : height    , width;
  13.         -webkit-transition-duration        : 0.5s        , 0.5s;
  14.         -webkit-transition-timing-function    : ease-in-out    , ease-in-out;
  15.         -webkit-transition-delay        : 0.0s        , 0.5s;
  16.     }

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:

  1.     nav > a:target  { -webkit-animation : pulse 1s infinite; }
  2.  
  3.     nav > a:target  {
  4.         -webkit-animation-name        : pulse;
  5.         -webkit-animation-duration        : 1s;
  6.         -webkit-animation-iteration-count    : infinite;
  7.     }

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

  1.     @-webkit-keyframes pulse  {
  2.         0%  { opacity : 1.0 }
  3.         50%  { opacity : 0.7 }
  4.     }

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:

  1.     @-webkit-keyframes slide_in  {
  2.       from  {
  3.         left            : 80%;
  4.         right           : -80%;
  5.       }
  6.       to  {
  7.         left            : 0em;
  8.         right           : 0em;
  9.       }
  10.     }

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.

  1.     @-webkit-keyframes banner_scroll  {
  2.         0%  { left    : 0%; }
  3.         18%  { left    : 0%; }
  4.         20%  { left    : -100%; }
  5.         38%  { left    : -100%; }
  6.         40%  { left    : -200%; }
  7.         58%  { left    : -200%; }
  8.         60%  { left    : -300%; }
  9.         78%  { left    : -300%; }
  10.         80%  { left    : -400%; }
  11.         95%  { left    : -400%; }
  12.         100%  { left : 0%; }
  13.     }

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.

Notes provided by the Qt Community

No notes