CSS3 Specification

Introduction to CSS3

W3C Working Draft, 23 May 2001

This version:
http://www.w3.org/TR/2001/WD-css3-roadmap-20010523/
Latest version:
http://www.w3.org/TR/css3-roadmap
Previous version:
http://www.w3.org/TR/2001/WD-css3-roadmap-20010406/
Editors:
Eric A. Meyer <eric@meyerweb.com>
Bert Bos (W3C) <bert@w3.org>

Copyright ?001 W3C ?/SUP> (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.

Abstract

The members of the CSS&FP Working Group have decided to modularize the CSS specification. This modularization will help to clarify the relationships between the different parts of the specification, and reduce the size of the complete document. It will also allow us to build specific tests on a per module basis and will help implementors in deciding which portions of CSS to support. Furthermore, the modular nature of the specification will make it possible for individual modules to be updated as needed, thus allowing for a more flexible and timely evolution of the specification as a whole.

This document lists all the modules to be contained in the future CSS3 specification.

Status of this document

This is an official introduction, issued by the CSS Working Group, which details the modularization of the CSS3 specification and the CSS test suite. This document should be considered to be informative, not normative. See the Style overview pages for more information on W3C's work on style sheets, including CSS.

This is a public W3C Working Draft for review by W3C members and other interested parties. As a draft document, it may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress."

A list of current W3C Recommendations and other technical documents including Working Drafts and Notes can be found at http://www.w3.org/TR/.

Please send comments to the www-style@w3.org mailing list (see how to subscribe) or to the editor.

Table of contents

  • 1. Why Modules?
  • 2. Module Overview
  • 3. Module Descriptions and Related Information
    • 3.1. Introduction
    • 3.2. Syntax / grammar
    • 3.3. Selectors
    • 3.4. Values & units
    • 3.5. Value assignment / cascade / inheritance
    • 3.6. Box model / vertical
    • 3.7. Positioning
    • 3.8. Color / gamma / color profiles
    • 3.9. Colors and Backgrounds
    • 3.10. Line box model
    • 3.11. Text
    • 3.12. Fonts
    • 3.13. Ruby
    • 3.14. Generated content / markers
    • 3.15. Replaced content
    • 3.16. Paged media
    • 3.17. User interface
    • 3.18. WebFonts
    • 3.19. ACSS
    • 3.20. SMIL
    • 3.21. Tables
    • 3.22. Columns
    • 3.23. SVG
    • 3.24. Math
    • 3.25. BECSS
    • 3.26. Media queries
    • 3.27. Test Suite
  • 4. Appendices
  • 5. Module template

1. Why Modules?

As the popularity of CSS grows, so does interest in making additions to the specification. Rather than attempting to shove dozens of updates into a single monolithic specification, it will be much easier and more efficient to be able to update individual pieces of the specification. Modules will enable CSS to be updated in a more timely and precise fashion, thus allowing for a more flexible and timely evolution of the specification as a whole.

For resource constrained devices, it may be impractical to support all of CSS. For example, an aural browser may be concerned only with aural styles, whereas a visual browser may care nothing for aural styles. In such cases, a user agent may implement a subset of CSS. Subsets of CSS are limited to combining selected CSS modules, and once a module has been chosen, all of its features must be supported.

2. Module Overview

All modules contain a "Conformance: Requirements and Recommendations" section. Any module whose table row is backed with green is considered part of the "CSS Core." The listed deadlines (backed in red) represent the time at which a module should be ready for Working Draft publication. There are also columns which indicate a module's participation in each of three "profiles": HTML Basic, CSS3, and SVG. A module without any indicated module participation is at risk of being dropped from CSS3 before it reaches Proposed Recommendation status. A module without a listed editor is backed in yellow, and is in serious danger of being dropped.

Module | Editor(s) | HTML Basic | CSS3 | SVG | WD1 | WD2 | LC | Ends | CR | PR | REC
Syntax / grammar / etc. |  | X | X |  | - | - | - | - | - | - | -
Selectors | Tantek Çelik, Daniel Glazman, Ian Hickson | X | X |  | 5 Oct 2000 | - | 26 Jan 2001 | 1 Mar 2001 | - | - | -
Values, Units | Håkon Lie, Chris Lilley | X | X |  | - | - | - | - | - | - | -
Value assignment / cascade / inheritance | Håkon Lie | X | X |  | - | - | - | - | - | - | -
Box model / vertical | Bert Bos | X | X |  | - | - | - | - | - | - | -
Positioning | Bert Bos |  | X |  | - | - | - | - | - | - | -
Color / gamma / color profiles | Tantek Çelik, Chris Lilley | X | X |  | 22 Jun 1999 | 5 Mar 2001 | - | - | - | - | -
Background | Tim Boland | X | X |  | - | - | - | - | - | - | -
Line box model | Eric Meyer | X | X |  | - | - | - | - | - | - | -
Text / bidi / vertical alignment | Chris Lilley, Michel Suignard | X | X |  | 17 May 2001 | - | - | - | - | - | -
Ruby | Michel Suignard |  | X |  | 16 Feb 2001 | - | - | - | - | - | -
Font properties | Chris Lilley, Michel Suignard | X | X |  | - | - | - | - | - | - | -
WebFonts | Chris Lilley |  | X |  | - | - | - | - | - | - | -
Generated content / markers | Håkon Lie |  | X |  | - | - | - | - | - | - | -
Replaced content | Eric Meyer |  | X |  | - | - | - | - | - | - | -
Paged media | Steve Zilles |  | X |  | 28 Sep 1999 | - | - | - | - | - | -
User interface | Tantek Çelik |  | X |  | 16 Sep 1999 | 16 Feb 2000 | - | - | - | - | -
Tables | Bert Bos | X | X |  | - | - | - | - | - | - | -
Columns | Håkon Lie |  | X |  | 22 Jun 1999 | 18 Jan 2001 | - | - | - | - | -
SVG | Chris Lilley |  | X | X | - | - | - | - | - | - | -
Math | Angel Diaz |  |  |  | - | - | - | - | - | - | -
BECSS | Michel Suignard |  |  |  | 4 Aug 1999 | - | - | - | - | - | -
ACSS |  |  |  |  | - | - | - | - | - | - | -
Media queries | Håkon W. Lie |  | X |  | 4 Apr 2001 | 17 May 2001 | - | - | - | - | -
SMIL | Debbie Newman |  |  |  | - | - | - | - | - | - | -
Test Suite | Eric Meyer |  | X |  | - | - | - | - | - | - | -

3. Module Descriptions and Related Information

3.1. Introduction

This provides a general overview of the specification's goals, as well as basic notes on how CSS works, acknowledgments, and so forth.

  • 1. About the CSS2 Specification
  • 2. Introduction to CSS2

3.2. Syntax / grammar

A way to attach arbitrary properties to a hierarchically structured document or other data structure, with the characteristic that it has built-in "forward-compatibility" (a.k.a. "extensibility").

  • 4. CSS2 syntax and basic data types
  • 7. Media types
  • Appendix D. The grammar of CSS2
  • Namespaces

3.3. Selectors

Describes the selectors of CSS3. Selectors are used to select elements in an HTML or XML document, in order to attach (style) properties to them. The draft includes the selectors of CSS1 and CSS2 and extends them with new proposals that allow, for example, elements to be selected based on whether they contain a certain word, or whether they are the only element of their kind.

  • 5. Selectors
  • 6.4.3. Specificity of selectors
  • Appendix D.1 Selectors' grammar
  • Namespaces

3.4. Values & units

Things which are applied to values.

  • 4.3. Values
  • Dynamic properties

3.5. Value assignment / cascade / inheritance

How properties interact, and the core of how CSS operates.

  • 6. Assigning property values, Cascading, and Inheritance

3.6. Box model / vertical

The box model describes the basics of the normal text flow, including how to "float" blocks of text or images, but excluding columns, tables, and other advanced layouts; i.e., it describes how text and other objects are strung into lines, and lines into blocks (paragraphs), and how those blocks are put below each other or side by side with the help of margins and borders. It treats both horizontal text and vertical writing modes.

  • 8. Box model
  • 9. Visual formatting model
  • 10. Visual formatting model details
  • 11. Visual effects
  • Floating boxes to top/bottom of page

3.7. Positioning

This describes the process of placing an element someplace other than it would normally be in the normal flow of the document.

  • 8. Box model
  • 9. Visual formatting model
  • 10. Visual formatting model details
  • 11. Visual effects
  • Floating boxes to top/bottom of page

3.8. Color / gamma / color profiles

In general, basic color descriptions and color handling in multiple environments. The color profiles section describes how two properties can be attached to embedded images to specify their "color space," which is the information a renderer needs to paint the right color for each pixel. It should do away with the annoying problem that images, especially GIF and JPEG, but sometimes also PNG, look different on a Mac than on a PC, or other platforms.

  • 14. Color
  • 14.1 Foreground color: the 'color' property
  • 14.3 Gamma correction
  • Transparency
  • Color profile for replaced elements

3.9. Colors and Backgrounds

A description of how element foregrounds and backgrounds are formatted.

  • 14.2. The background

3.10. Line box model

A description of the line box model for inline elements, and the inline content of block elements.

  • Inline model document

3.11. Text

Description of the handling of text in user agents. Includes bidi, vertical alignment, text decoration, line breaking, etc.

  • 16. Text
  • Copy-fitting/auto-sizing/auto-spacing
  • "International layout"

3.12. Fonts

POWERED BY HeroNote

Description of the handling of fonts in user agents.

  • 15. Fonts

3.13. Ruby

A draft that contains proposals for new style properties for typographic traditions that have so far had little attention in CSS, such as vertical Japanese and Arabic. The CSS working group is cooperating with W3C's Internationalization working group on this.

  • The Internationalization CSS WD

3.14. Generated content / markers

A description of how content is generated and markers are displayed.

  • 12. Generated content, automatic numbering, and lists

3.15. Replaced content

A module explaining how replaced content is handled and what qualifies as replaced content.

  • ???

3.16. Paged media

Extends the properties that CSS2 already had with new ones to control such things as running headers and footers, page numbers and print-style cross-references ("see page...").

  • 13. Paged media
  • The CSS3 Page WD
  • Running headers and footers
  • Cross-references
  • Float : gutter-side/fore-edge-side
  • Floating boxes to top/bottom of page

3.17. User interface

Contains features for styling some interactive, dynamic aspects of Web pages: the look of form elements in their various states, more cursors and colors to describe GUIs (graphical user interfaces) that blend well with the user's desktop environment, and a proposal for "kiosk" mode.

  • 18. User interface
  • The UI/Forms WD
  • Rendering objects for forms

3.18. WebFonts

Authors continue to clamor for "more control" over their pages, and the fonts used in presenting them. This module will attempt to provide a way to make fonts more Web-friendly.

  • 15. Fonts
  • Appendix C. Implementation and performance notes for fonts
  • Appendix G. Descriptor index

3.19. ACSS

An attempt to make styled content even more accessible.

  • 19. Aural style sheets
  • Accessibility features of CSS

3.20. SMIL

An attempt to link CSS and SMIL together.

  • SMIL 1.0
  • SYMM

3.21. Tables

The tables module contains the properties to lay out boxes in rows and columns. It allows a designer to assign roles like "table," "cell," "row," or "caption" to boxes and provides for various alignments and border styles.

  • 17. Tables

3.22. Columns

Proposes new properties to create flexible column layouts.

  • Multicolumn layout in CSS

3.23. SVG

A format that expresses shapes (lines, circles, splines, etc.) in an XML-based language and their style (fill color, stroke width, etc.) in CSS. This should make it easy to create text and graphics in the same style simply by using a single style sheet for both. SVG uses several existing CSS properties, but also introduces new ones that may or may not be useful for styling text. It will progress to Recommendation as a separate specification, but the (new) CSS properties are coordinated with the CSS working group.

  • SVG

3.24. Math

An attempt to provide style properties for mathematical expressions. This will obviously be deeply linked to the MathML specification.

  • MathML 1.0

3.25. BECSS

A proposal to use the CSS syntax and CSS's system of cascading and inheritance to attach "behavior" (rather than style) to elements. Behavior in this context refers to any dynamic changes to the style or the document in response to user events, such as clicks and key presses. The behaviors themselves are expressed as pieces of script, in languages such as ECMAscript.

  • BECSS draft

3.26. Media queries

To describe in more detail what type of devices a style sheet applies to, this document proposes media queries. A media query consists of a media type and one or more expressions to limit the scope of a certain style sheet. Among the proposed media features that can be used in expressions are "width", "height" (size of the display), and "color" (color depth of the display).

3.27. Test Suite

Providing implementation guidelines, concrete examples, and user insight into implementation support, a test suite is crucial to the success of any specification. Although the Test Suite is a module in itself and has a module owner, individual module owners are responsible for assisting in the creation and review of tests for their specific module.

  • CSS1 Test Suite

4. Appendices

Some appendices will be split up to go with individual modules. These are:

  • Appendix B. Changes from CSS1
  • Appendix E. References
  • Appendix F. Property index

For example, the changes between one version of a module and another should be tracked in an appendix to that module, not a single appendix to the entire specification. Similarly, there should be a property reference for each module. There may be a single cumulative reference for the entire specification, although this is not yet known with any certainty. Each module should also include an appendix listing any dependencies on other modules or specifications.

There will also be a few specification-wide appendices. There are projected to be:

  • Appendix A. A sample style sheet for HTML 4.0
  • Appendix H. Index

5. Module template

All modules should conform to the format defined in the CSS3 editing rules [member-only link]. In addition to the definitions of properties and values, each module contains a list of dependencies on other modules or specifications, and also provides a list of changes from CSS2.


CSS3 2D Transforms Module

CSS 2D Transforms Module Level 3

W3C Working Draft 01 December 2009

This version:
http://www.w3.org/TR/2009/WD-css3-2d-transforms-20091201
Latest version:
http://www.w3.org/TR/css3-2d-transforms
Previous version:
http://www.w3.org/TR/2009/WD-css3-2d-transforms-20090320
Editors:
Dean Jackson (Apple Inc)
David Hyatt (Apple Inc)
Chris Marrin (Apple Inc)

Copyright © 2009 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

CSS 2D Transforms allows elements rendered by CSS to be transformed in two-dimensional space.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css3-2d-transforms” in the subject, preferably like this: “[css3-2d-transforms] …summary of comment…”

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

The list of changes made to this specification is available.

Table of contents

  • 1. Introduction
  • 2. The ‘transform’ Property
  • 3. The ‘transform-origin’ Property
  • 4. The Transformation Functions
  • 5. Transform Values and Lists
  • 6. Transitions and animations between transform values
  • 7. Matrix decomposition for animation
  • 8. DOM Interfaces
    • 8.1. CSSMatrix
  • 9. References
    • Normative references
    • Other references
  • Property index
  • Index

1. Introduction

This section is not normative.

The CSS visual formatting model describes a coordinate system within which each element is positioned. Positions and sizes in this coordinate space can be thought of as being expressed in pixels, starting in the upper left corner of the parent with positive values proceeding to the right and down.

This coordinate space can be modified with the ‘transform’ property. Using transform, elements can be translated, rotated and scaled in two dimensional space. The coordinate space behaves as described in the coordinate system transformations section of the SVG 1.1 specification. This is a coordinate system with two axes: the X axis increases horizontally to the right; the Y axis increases vertically downwards.

Specifying a value other than ‘none’ for the ‘transform’ property establishes a new local coordinate system at the element that it is applied to. Transformations are cumulative. That is, elements establish their local coordinate system within the coordinate system of their parent. In this way, a ‘transform’ property effectively accumulates all the ‘transform’ properties of its ancestors. The accumulation of these transforms defines a current transformation matrix (CTM) for the element.

The transform property does not affect the flow of the content surrounding the transformed element. However, the value of the overflow area takes into account transformed elements. This behavior is similar to what happens when elements are translated via relative positioning. Therefore, if the value of the ‘overflow’ property is ‘scroll’ or ‘auto’, scrollbars will appear as needed to see content that is transformed outside the visible area.

Any value other than ‘none’ for the transform results in the creation of both a stacking context and a containing block. The object acts as a containing block for fixed positioned descendants.

Need to go into more detail here about why fixed positioned objects should do this, i.e., that it's much harder to implement otherwise.
There are two roles for transformations in layout: (1) transformations that adjust the position of the affected content without changing the normal layout of that content (much like relative positioning) and (2) transformation of the content prior to layout that affects the layout of that content. See http://lists.w3.org/Archives/Public/www-style/2007Oct/0209 for examples of both cases. The "transform" property (as defined in this document) is equally useful for both roles. This document is focused on satisfying the first role. There is, however, an architectural question that arises because there needs to be a way to distinguish which role an author of a stylesheet wants. The key question is which is the default behavior/role for the "transform" property and how is the other behavior/role indicated by a stylesheet author. If you have an opinion on this topic, please send feedback.
What do fixed backgrounds do in transforms? They should probably ignore the transform completely, since - even transformed - the object should be acting as "porthole" through which the fixed background can be viewed in its original form.
This property should also be applicable to SVG elements.
We also need to specify that SVG transforms *do* combine with this transform, e.g., if a <foreignObject> is inside transformed SVG and then defines a transform of its own. This means we may potentially have to examine the current SVG transform and combine with it to set the correct transform.

2. The ‘transform’ Property

A two-dimensional transformation is applied to an element through the ‘transform’ property. This property contains a list of transform functions. The final transformation value for an element is obtained by performing a matrix concatenation of each entry in the list. The set of transform functions is similar to those allowed by SVG.

Name: | transform
Value: | none | <transform-function> [ <transform-function> ]*
Initial: | none
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | refer to the size of the element's box
Media: | visual
Computed value: | Same as specified value.

3. The ‘transform-origin’ Property

The ‘transform-origin’ property establishes the origin of transformation for an element. This property is applied by first translating the element by the negated value of the property, then applying the element's transform, then translating by the property value. This effectively moves the desired transformation origin of the element to (0,0) in the local coordinate system, then applies the element's transform, then moves the element back to its original position.

If only one value is specified, the second value is assumed to be ‘center’. If at least one value is not a keyword, then the first value represents the horizontal position and the second represents the vertical position. Negative <percentage> and <length> values are allowed.

Name: | transform-origin
Value: | [ [ <percentage> | <length> | left | center | right ] [ <percentage> | <length> | top | center | bottom ]? ] | [ [ left | center | right ] || [ top | center | bottom ] ]
Initial: | 50% 50%
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | refer to the size of the element's box
Media: | visual
Computed value: | For <length> the absolute value, otherwise a percentage

4. The Transformation Functions

The value of the transform property is a list of <transform-functions> applied in the order provided. The individual transform functions are separated by whitespace. The set of allowed transform functions is given below. In this list the type <translation-value> is defined as a <length> or <percentage> value, and the <angle> type is defined by CSS Values and Units.

matrix(<number>, <number>, <number>, <number>, <number>, <number>)
specifies a 2D transformation in the form of a transformation matrix of six values. matrix(a,b,c,d,e,f) is equivalent to applying the transformation matrix [a b c d e f].
translate(<translation-value>[, <translation-value>])
specifies a 2D translation by the vector [tx, ty], where tx is the first translation-value parameter and ty is the optional second translation-value parameter. If <ty> is not provided, ty has zero as a value.
translateX(<translation-value>)
specifies a translation by the given amount in the X direction.
translateY(<translation-value>)
specifies a translation by the given amount in the Y direction.
scale(<number>[, <number>])
specifies a 2D scale operation by the [sx,sy] scaling vector described by the 2 parameters. If the second parameter is not provided, it is takes a value equal to the first.
scaleX(<number>)
specifies a scale operation using the [sx,1] scaling vector, where sx is given as the parameter.
scaleY(<number>)
specifies a scale operation using the [1,sy] scaling vector, where sy is given as the parameter.
rotate(<angle>)
specifies a 2D rotation by the angle specified in the parameter about the origin of the element, as defined by the transform-origin property.
skewX(<angle>)
specifies a skew transformation along the X axis by the given angle.
skewY(<angle>)
specifies a skew transformation along the Y axis by the given angle.
skew(<angle> [, <angle>])
specifies a skew transformation along the X and Y axes. The first angle parameter specifies the skew on the X axis. The second angle parameter specifies the skew on the Y axis. If the second parameter is not given then a value of 0 is used for the Y angle (ie. no skew on the Y axis).

5. Transform Values and Lists

The <translation-value> values are defined as [<percentage> | <length>]. All other value types are described as CSS types. If a list of transforms is provided, then the net effect is as if each transform had been specified separately in the order provided. For example,

POWERED BY HeroNote
  <div style="transform:translate(-10px,-20px) scale(2) rotate(45deg) translate(5px,10px)"/>

is functionally equivalent to:

  <div style="transform:translate(-10px,-20px)">
    <div style="transform:scale(2)">
      <div style="transform:rotate(45deg)">
        <div style="transform:translate(5px,10px)">
        </div>
      </div>
    </div>
  </div>

  div {
      transform: translate(100px, 100px);
  }
Move the element by 100 pixels in both the X and Y directions.
The 100px translation in X and Y
  div {
      height: 100px; width: 100px;
      transform: translate(80px, 80px) scale(1.5, 1.5) rotate(45deg);
  }
Move the element by 80 pixels in both the X and Y directions, then scale the element by 150%, then rotate it 45 degrees clockwise about the Z axis. Note that the scale and rotate operate about the center of the element, since the element has the default transform-origin of 50% 50%.
The transform specified above

6. Transitions and animations between transform values

When animating or transitioning the value of a transform property the rules described below are applied. The ‘from’ transform is the transform at the start of the transition or current keyframe. The ‘end’ transform is the transform at the end of the transition or current keyframe.

  • If the ‘from’ and ‘to’ transforms are both single functions of the same type:
    • For translate, translateX, translateY, scale, scaleX, scaleY, rotate, skew, skewX and skewY functions:
      • the individual components of the function are interpolated numerically.
    • For matrix:
      • the matrix is decomposed using the method described by unmatrix into separate translation, scale, rotation and skew matrices, then each decomposed matrix is interpolated numerically, and finally combined in order to produce a resulting 3x2 matrix.
  • If both the ‘from’ and ‘to’ transforms are "none":
    • There is no interpolation necessary
  • If one of the ‘from’ or ‘to’ transforms is "none":
    • The ‘none’ is replaced by an equivalent identity function list for the corresponding transform function list.

      For example, if the ‘from’ transform is "scale(2)" and the ‘to’ transform is "none" then the value "scale(1)" will be used as the ‘to’ value, and animation will proceed using the rule above. Similarly, if the ‘from’ transform is "none" and the ‘to’ transform is "scale(2) rotate(50deg)" then the animation will execute as if the ‘from’ value is "scale(1) rotate(0)".

      The identity functions are translate(0), translateX(0), translateY(0), scale(1), scaleX(1), scaleY(1), rotate(0), rotateX(0), rotateY(0), skewX(0), skewY(0), skew(0, 0) and matrix(1, 0, 0, 1, 0, 0).

  • If both the ‘from’ and ‘to’ transforms have the same number of transform functions and corresponding functions in each transform list are of the same type:
    • Each transform function is animated with its corresponding destination function in isolation using the rules described above. The individual values are then applied as a list to produce resulting transform value.
  • Otherwise:
    • The transform function lists are each converted into the equivalent matrix value and animation proceeds using the rule for a single function above.

In some cases, an animation might cause a transformation matrix to be singular or non-invertible. For example, an animation in which scale moves from 1 to -1. At the time when the matrix is in such a state, the transformed element is not rendered.

7. Matrix decomposition for animation

When interpolating between 2 matrices, each is decomposed into the corresponding translation, rotation, scale, skew, and perspective values. Not all matrices can be accurately described by these values. Those that can't are decomposed into the most accurate representation possible, using the technique below. This technique is taken from The "unmatrix" method in "Graphics Gems II, edited by Jim Arvo". The pseudocode below works on a 4x4 homogeneous matrix. A 3x2 2D matrix is therefore first converted to 4x4 homogeneous form.

  Input: matrix       ; a 4x4 matrix
  Output: translation ; a 3 component vector
          rotation    ; Euler angles, represented as a 3 component vector
          scale       ; a 3 component vector
          skew        ; skew factors XY,XZ,YZ represented as a 3 component vector
          perspective ; a 4 component vector
  Returns false if the matrix cannot be decomposed, true if it can

    Supporting functions (point is a 3 component vector, matrix is a 4x4 matrix):
      float  determinant(matrix)          returns the 4x4 determinant of the matrix
      matrix inverse(matrix)              returns the inverse of the passed matrix
      matrix transpose(matrix)            returns the transpose of the passed matrix
      point  multVecMatrix(point, matrix) multiplies the passed point by the passed matrix
                                          and returns the transformed point
      float  length(point)                returns the length of the passed vector
      point  normalize(point)             normalizes the length of the passed point to 1
      float  dot(point, point)            returns the dot product of the passed points
      float  cos(float)                   returns the cosine of the passed angle in radians
      float  asin(float)                  returns the arcsine in radians of the passed value
      float  atan2(float y, float x)      returns the principal value of the arc tangent of
                                          y/x, using the signs of both arguments to determine
                                          the quadrant of the return value

    Decomposition also makes use of the following function:
      point combine(point a, point b, float ascl, float bscl)
          result[0] = (ascl * a[0]) + (bscl * b[0])
          result[1] = (ascl * a[1]) + (bscl * b[1])
          result[2] = (ascl * a[2]) + (bscl * b[2])
          return result

    // Normalize the matrix.
    if (matrix[3][3] == 0)
        return false

    for (i = 0; i < 4; i++)
        for (j = 0; j < 4; j++)
            matrix[i][j] /= matrix[3][3]

    // perspectiveMatrix is used to solve for perspective, but it also provides
    // an easy way to test for singularity of the upper 3x3 component.
    perspectiveMatrix = matrix

    for (i = 0; i < 3; i++)
        perspectiveMatrix[i][3] = 0

    perspectiveMatrix[3][3] = 1

    if (determinant(perspectiveMatrix) == 0)
        return false

    // First, isolate perspective.
    if (matrix[0][3] != 0 || matrix[1][3] != 0 || matrix[2][3] != 0)
        // rightHandSide is the right hand side of the equation.
        rightHandSide[0] = matrix[0][3];
        rightHandSide[1] = matrix[1][3];
        rightHandSide[2] = matrix[2][3];
        rightHandSide[3] = matrix[3][3];

        // Solve the equation by inverting perspectiveMatrix and multiplying
        // rightHandSide by the inverse.
        inversePerspectiveMatrix = inverse(perspectiveMatrix)
        transposedInversePerspectiveMatrix = transposeMatrix4(inversePerspectiveMatrix)
        perspective = multVecMatrix(rightHandSide, transposedInversePerspectiveMatrix)

         // Clear the perspective partition
        matrix[0][3] = matrix[1][3] = matrix[2][3] = 0
        matrix[3][3] = 1
    else
        // No perspective.
        perspective[0] = perspective[1] = perspective[2] = 0
        perspective[3] = 1

    // Next take care of translation
    translate[0] = matrix[3][0]
    matrix[3][0] = 0
    translate[1] = matrix[3][1]
    matrix[3][1] = 0
    translate[2] = matrix[3][2]
    matrix[3][2] = 0

    // Now get scale and shear. 'row' is a 3 element array of 3 component vectors
    for (i = 0; i < 3; i++)
        row[i][0] = matrix[i][0]
        row[i][1] = matrix[i][1]
        row[i][2] = matrix[i][2]

    // Compute X scale factor and normalize first row.
    scale[0] = length(row[0])
    row[0] = normalize(row[0])

    // Compute XY shear factor and make 2nd row orthogonal to 1st.
    skew[0] = dot(row[0], row[1])
    row[1] = combine(row[1], row[0], 1.0, -skew[0])

    // Now, compute Y scale and normalize 2nd row.
    scale[1] = length(row[1])
    row[1] = normalize(row[1])
    skew[0] /= scale[1];

    // Compute XZ and YZ shears, orthogonalize 3rd row
    skew[1] = dot(row[0], row[2])
    row[2] = combine(row[2], row[0], 1.0, -skew[1])
    skew[2] = dot(row[1], row[2])
    row[2] = combine(row[2], row[1], 1.0, -skew[2])

    // Next, get Z scale and normalize 3rd row.
    scale[2] = length(row[2])
    row[2] = normalize(row[2])
    skew[1] /= scale[2]
    skew[2] /= scale[2]

    // At this point, the matrix (in rows) is orthonormal.
    // Check for a coordinate system flip.  If the determinant
    // is -1, then negate the matrix and the scaling factors.
    pdum3 = cross(row[1], row[2])
    if (dot(row[0], pdum3) < 0)
        for (i = 0; i < 3; i++) {
            scale[0] *= -1;
            row[i][0] *= -1
            row[i][1] *= -1
            row[i][2] *= -1

    // Now, get the rotations ou
    rotate[1] = asin(-row[0][2]);
    if (cos(rotate[1]) != 0)
       rotate[0] = atan2(row[1][2], row[2][2]);
       rotate[2] = atan2(row[0][1], row[0][0]);
    else
       rotate[0] = atan2(-row[2][0], row[1][1]);
       rotate[2] = 0;

    return true;

Each component of each returned value is linearly interpolated with the corresponding component of the other matrix. The resulting components are then recomposed into a final matrix as though combining the following transform functions:

        matrix3d(1,0,0,0, 0,1,0,0, 0,0,1,0, perspective[0], perspective[1], perspective[2], perspective[3])
        translate3d(translation[0], translation[1], translation[2])
        rotateX(rotation[0]) rotateY(rotation[1]) rotateZ(rotation[2])
        matrix3d(1,0,0,0, 0,1,0,0, 0,skew[2],1,0, 0,0,0,1)
        matrix3d(1,0,0,0, 0,1,0,0, skew[1],0,1,0, 0,0,0,1)
        matrix3d(1,0,0,0, skew[0],1,0,0, 0,0,1,0, 0,0,0,1)
        scale3d(scale[0], scale[1], scale[2])

8. DOM Interfaces

This section describes the interfaces and functionality added to the DOM to support runtime access to the functionality described above.

8.1. CSSMatrix

Interface CSSMatrix

The CSSMatrix interface represents a 4x4 homogeneous matrix.

IDL Definition
  interface CSSMatrix {
      attribute float a;
      attribute float b;
      attribute float c;
      attribute float d;
      attribute float e;
      attribute float f;

      void        setMatrixValue(in DOMString string) raises(DOMException);
      CSSMatrix   multiply(in CSSMatrix secondMatrix);
      CSSMatrix   multiplyLeft(in CSSMatrix secondMatrix);
      CSSMatrix   inverse() raises(DOMException);
      CSSMatrix   translate(in float x, in float y);
      CSSMatrix   scale(in float scaleX, in float scaleY);
      CSSMatrix   skew(in float angleX, in float angleY);
      CSSMatrix   rotate(in float angle);
  };

Attributes
a-f of type float
Each of these attributes represents one of the values in the 3x2 matrix.
Methods
setMatrixValue
The setMatrixValue method replaces the existing matrix with one computed from parsing the passed string as though it had been assigned to the transform property in a CSS style rule.
Parameters
string of type DOMString
The string to parse.
No Return Value
Exceptions
DOMException SYNTAX_ERR
Thrown when the provided string can not be parsed into a CSSMatrix.
multiply
The multiply method returns a new CSSMatrix which is the result of this matrix multiplied by the passed matrix, with the passed matrix to the right. This matrix is not modified.
Parameters
secondMatrix of type CSSMatrix
The matrix to multiply.
Return Value
CSSMatrix
The result matrix.
No Exceptions
multiplyLeft
The multiplyLeft method returns a new CSSMatrix which is the result of this matrix multiplied by the passed matrix, with the passed matrix to the left. This matrix is not modified.
Parameters
secondMatrix of type CSSMatrix
The matrix to multiply.
Return Value
CSSMatrix
The result matrix.
No Exceptions
inverse
The inverse method returns a new matrix which is the inverse of this matrix. This matrix is not modified.
No Parameters
Return Value
CSSMatrix
The inverted matrix.
Exceptions
DOMException NOT_SUPPORTED_ERR
Thrown when the CSSMatrix can not be inverted.
translate
The translate method returns a new matrix which is this matrix post multiplied by a translation matrix containing the passed values. This matrix is not modified.
Parameters
x of type float
The X component of the translation value.
y of type float
The Y component of the translation value.
Return Value
CSSMatrix
The result matrix.
No Exceptions
scale
The scale method returns a new matrix which is this matrix post multiplied by a scale matrix containing the passed values. If the y component is undefined, the x component value is used in its place. This matrix is not modified.
Parameters
scaleX of type float
The X component of the scale value.
scaleY of type float
The (optional) Y component of the scale value.
Return Value
CSSMatrix
The result matrix.
No Exceptions
rotate
The rotate method returns a new matrix which is this matrix post multiplied by a rotation matrix. The rotation value is in degrees. This matrix is not modified.
Parameters
angle of type float
The angle of rotation.
Return Value
CSSMatrix
The result matrix.
No Exceptions
skew
The skew method returns a new matrix which is this matrix post multiplied by a skew matrix. The rotation value is in degrees. This matrix is not modified.
Parameters
angleX of type float
The angle of skew along the X axis.
angleY of type float
The angle of skew along the Y axis.
Return Value
CSSMatrix
The result matrix.
No Exceptions

In addition to the interface listed above, the getComputedStyle method of the Window object has been updated. The transform property of the style object returned by getComputedStyle contains a DOMString of the form "matrix(a, b, c, d, e, f)" representing the 3x2 matrix that is the result of applying the individual functions listed in the transform property.

9. References

Normative references

Other references

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
transform | none | <transform-function> [ <transform-function> ]* | none | block-level and inline-level elements | no | refer to the size of the element's box | visual
transform-origin | [ [ <percentage> | <length> | left | center | right ] [ <percentage> | <length> | top | center | bottom ]? ] | [ [ left | center | right ] || [ top | center | bottom ] ] | 50% 50% | block-level and inline-level elements | no | refer to the size of the element's box | visual

Index

  • transform, 2.
  • transform-origin, 3.


CSS3 3D Transforms Module

CSS 3D Transforms Module Level 3

W3C Working Draft 20 March 2009

This version:
http://www.w3.org/TR/2009/WD-css3-3d-transforms-20090320
Latest version:
http://www.w3.org/TR/css3-3d-transforms
Previous version:
none
Editors:
Dean Jackson (Apple Inc)
David Hyatt (Apple Inc)
Chris Marrin (Apple Inc)

Copyright ?2009 W3C ?/SUP> (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

CSS 3D Transforms extends CSS Transforms to allow elements rendered by CSS to be transformed in three-dimensional space.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text "css3-3d-transforms" in the subject, preferably like this: "[css3-3d-transforms] .summary of comment."

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This is the first public Working Draft of the "css3-3d-transforms" series.

Table of contents

  • 1 Introduction
  • 2 The 'transform' Property
  • 3 The 'transform-origin' Property
  • 4 The 'transform-style' Property
  • 5 The 'perspective' Property
  • 6 The 'perspective-origin' Property
  • 7 The 'backface-visibility' Property
  • 8 The Transformation Functions
  • 9 Transitions and animations between transform values
  • 10 DOM Interfaces
    • 10.1 10.1 CSSMatrix
    • 10.2 10.2 CSSTransformValue
  • 11 References
    • Normative references
    • Other references
  • Property index
  • Index

1 Introduction

This section is not normative.

This is an enhancement to the CSS Transforms specification which provides transforms in three dimensions. It should be read in conjunction with that specification.

This coordinate space can be modified with the 'transform' property. Using transform, elements can be translated, rotated and scaled in two or three dimensional space. A perspective transform can also be applied to give a sense of depth to the way elements are displayed. In three dimensions, a Z axis is added, with positive z values conceptually rising perpendicularly out of the window toward the user and negative z values falling into the window away from the user.

Any value other than 'none' for the transform results in the creation of both a stacking context and a containing block. The object acts as though position: relative has been specified, but also acts as a containing block for fixed positioned descendants. The position on the Z axis of a transformed element does not affect the order within a stacking context. With elements at the same z-index, objects are drawn in order of increasing z position.

Note that while 'transform' uses a three-dimensional coordinate system, the elements themselves are not three-dimensional objects. Instead, they exist on a two-dimensional plane (a flat surface) and have no depth.

2 The 'transform' Property

A 2D or 3D transformation is applied to an element through the 'transform' property. This property contains a list of transform functions. The final transformation value for an element is obtained by performing a matrix concatenation of each entry in the list. The set of transform functions is similar to those allowed by SVG. There are additional functions to support 3D transformations.

Name: | transform
Value: | none | <transform-function> [ <transform-function> ]*
Initial: | none
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | refer to the size of the element's box
Media: | visual
Computed value: | Same as specified value.

3 The 'transform-origin' Property

The 'transform-origin' property establishes the origin of transformation for an element. This property is applied by first translating the element by the negated value of the property, then applying the element's transform, then translating by the property value. This effectively moves the desired transformation origin of the element to (0,0,0) in the local coordinate system, then applies the element's transform, then moves the element back to its original position.

Name: | transform-origin
Value: | [ [ [ <percentage> | <length> | left | center | right ] [ <percentage> | <length> | top | center | bottom ]? ] <length> ] | [ [ [ left | center | right ] || [ top | center | bottom ] ] <length> ]
Initial: | 50% 50% 0
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | refer to the size of the element's box
Media: | visual
Computed value: | For <length> the absolute value, otherwise a percentage

4 The 'transform-style' Property

The 'transform-style' property defines how nested elements are rendered in 3D space. If the 'transform-style' is 'flat', all children of this element are rendered flattened into the 2D plane of the element. Therefore, rotating the element about the X or Y axes will cause children positioned at positive or negative Z positions to appear on the element's plane, rather than in front of or behind it. If the 'transform-style' is 'preserve-3d', this flattening is not performed, so children maintain their position in 3D space.

This flattening takes place at each element, so preserving a hierarchy of elements in 3D space requires that each ancestor in the hierarchy have the value 'preserve-3d' for 'transform-style'. But since 'transform-style' affects only an element's children, the leaf nodes in a hierarchy do not require the perspective style.

Name: | transform-style
Value: | flat | preserve-3d
Initial: | flat
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | Same as specified value.

For some effects, the author will have to ensure that an ancestor element to a subtree using 'preserve-3d' has a 'transform-style' of 'flat' (or the default). Otherwise, the elements in the 3D tree may be located behind ancestor elements and, thus, invisible (hidden behind an ancestor's background).

Note that while 'preserve-3d' can be specified on an element, the effect may not be possible. Elements that have 'overflow' set to 'hidden' are unable to keep their children in 3D. In this case the element will behave as if the property was set to 'flat'.

Does transform-style: preserve-3d need to establish a stacking context and containing block like transform does?

5 The 'perspective' Property

The 'perspective' property applies the same transform as the perspective(<number>) transform function, except that it applies only to the positioned or transformed children of the element, not to the transform on the element itself.

If the value is 'none', less than or equal to 0 no perspective transform is applied.

The use of this property with any value other than 'none' establishes a stacking context. It also establishes a containing block (somewhat similar to position:relative), just like the 'transform' property does.

Name: | perspective
Value: | none | <number>
Initial: | none
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | Same as specified value.

6 The 'perspective-origin' Property

The 'perspective-origin' property establishes the origin for the perspective property. It effectively sets the X and Y position at which the viewer appears to be looking at the children of the element.

Name: | perspective-origin
Value: | [ [ <percentage> | <length> | left | center | right ] [ <percentage> | <length> | top | center | bottom ]? ] | [ [ left | center | right ] || [ top | center | bottom ] ]
Initial: | 50% 50%
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | refer to the size of the box itself
Media: | visual
Computed value: | Same as specified value.

POWERED BY HeroNote

7 The 'backface-visibility' Property

The 'backface-visibility' property determines whether or not the "back" side of a transformed element is visible when facing the viewer. With an identity transform, the front side of an element faces the viewer. Applying a rotation about Y of 180 degrees (for instance) would cause the back side of the element to face the viewer.

This property is useful when you place two elements back-to-back, as you would to create a playing card. Without this property, the front and back elements could switch places at times during an animation to flip the card. Another example is creating a box out of 6 elements, but where you want to see the inside faces of the box. This is useful when creating the backdrop for a 3 dimensional stage.

Name: | backface-visibility
Value: | visible | hidden
Initial: | visible
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | Same as specified value.

8 The Transformation Functions

The value of the transform property is a list of <transform-functions>, applied in the order provided. The individual transform functions are separated by whitespace. The following is a list of allowed transform functions. In this list the type <translation-value> is defined as a <length> or <percentage> value, and the <angle> type is defined by CSS Values and Units.

matrix(<number>, <number>, <number>, <number>, <number>, <number>)
specifies a 2D transformation in the form of a transformation matrix of six values. matrix(a,b,c,d,e,f) is equivalent to matrix3d(a, b, 0, 0, c, d, 0, 0, 0, 0, 1, 0, e, f, 0, 1).
matrix3d(<number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>, <number>)
specifies a 3D transformation as a 4x4 homogeneous matrix of 16 values in column-major order.
translate(<translation-value>[, <translation-value>])
specifies a 2D translation by the vector [tx, ty], where tx is the first translation-value parameter and ty is the optional second translation-value parameter. If <ty> is not provided, ty has zero as a value.
translate3d(<translation-value>, <translation-value>, <translation-value>)
specifies a 3D translation by the vector [tx,ty,tz], with tx, ty and tz being the first, second and third translation-value parameters respectively.
translateX(<translation-value>)
specifies a translation by the given amount in the X direction.
translateY(<translation-value>)
specifies a translation by the given amount in the Y direction.
translateZ(<translation-value>)
specifies a translation by the given amount in the Z direction. Note that percentage values are not allowed in the translateZ translation-value, and if present are evaluated as 0.
scale(<number>[, <number>])
specifies a 2D scale operation by the [sx,sy] scaling vector described by the 2 parameters. If the second parameter is not provided, it is takes a value equal to the first.
scale3d(<number>, <number>, <number>)
specifies a 3D scale operation by the [sx,sy,sz] scaling vector described by the 3 parameters.
scaleX(<number>)
specifies a scale operation using the [sx,1,1] scaling vector, where sx is given as the parameter.
scaleY(<number>)
specifies a scale operation using the [1,sy,1] scaling vector, where sy is given as the parameter.
scaleZ(<number>)
specifies a scale operation using the [1,1,sz] scaling vector, where sz is given as the parameter.
rotate(<angle>)
specifies a 2D rotation by the angle specified in the parameter about the origin of the element, as defined by the transform-origin property.
rotate3d(<number>, <number>, <number>, <angle>)
specifies a clockwise 3D rotation by the angle specified in last parameter about the [x,y,z] direction vector described by the first 3 parameters. If the direction vector is not of unit length, it will be normalized. A direction vector that cannot be normalized, such as [0, 0, 0], will cause the rotation to not be applied. This function is equivalent to matrix3d(1 + (1-cos(angle))*(x*x-1), -z*sin(angle)+(1-cos(angle))*x*y, y*sin(angle)+(1-cos(angle))*x*z, 0, z*sin(angle)+(1-cos(angle))*x*y, 1 + (1-cos(angle))*(y*y-1), -x*sin(angle)+(1-cos(angle))*y*z, 0, -y*sin(angle)+(1-cos(angle))*x*z, x*sin(angle)+(1-cos(angle))*y*z, 1 + (1-cos(angle))*(z*z-1), 0, 0, 0, 0, 1).
rotateX(<angle>)
specifies a clockwise rotation by the given angle about the X axis.
rotateY(<angle>)
specifies a clockwise rotation by the given angle about the Y axis.
rotateZ(<angle>)
specifies a clockwise rotation by the given angle about the Z axis.
skewX(<angle>)
specifies a skew transformation along the X axis by the given angle.
skewY(<angle>)
specifies a skew transformation along the Y axis by the given angle.
skew(<angle> [, <angle>])
specifies a skew transformation along the X and Y axes. The first angle parameter specifies the skew on the X axis. The second angle parameter specifies the skew on the Y axis. If the second parameter is not given then a value of 0 is used for the Y angle (ie. no skew on the Y axis).
perspective(<number>)
specifies a perspective projection matrix. This matrix maps a viewing cube onto a pyramid whose base is infinitely far away from the viewer and whose peak represents the viewer's position. The viewable area is the region bounded by the four edges of the viewport (the portion of the browser window used for rendering the webpage between the viewer's position and a point at a distance of infinity from the viewer). The depth, given as the parameter to the function, represents the distance of the z=0 plane from the viewer. Lower values give a more flattened pyramid and therefore a more pronounced perspective effect. The value is given in pixels, so a value of 1000 gives a moderate amount of foreshortening and a value of 200 gives an extreme amount. The matrix is computed by starting with an identity matrix and replacing the value at row 3, column 4 with the value -1/depth. The value for depth must be greater than zero, otherwise the function is invalid.

9 Transitions and animations between transform values

When animating or transitioning the value of a transform property the rules described below are applied. The 'from' transform is the transform at the start of the transition or current keyframe. The 'end' transform is the transform at the end of the transition or current keyframe.

  • If the 'from' and 'to' transforms are both single functions of the same type:
    • For translate, translate3d, translateX, translateY, translateZ, scale, scale3d, scaleX, scaleY, scaleZ, rotate, rotateX, rotateY, rotateZ, skewX and skewY functions:
      • the individual components of the function are interpolated numerically.
    • For perspective, matrix, matrix3d and rotate3d:
      • the values are first converted to a 4x4 matrix, then decomposed using the method described by unmatrix into separate translation, scale, rotation, skew and perspective matrices, then each decomposed matrix is interpolated numerically, and finally combined in order to produce a resulting 4x4 matrix.
  • If both the 'from' and 'to' transforms are "none":
    • There is no interpolation necessary
  • If one of the 'from' or 'to' transforms is "none":
    • The 'none' is replaced by an equivalent identity function list for the corresponding transform function list.

      For example, if the 'from' transform is "scale(2)" and the 'to' transform is "none" then the value "scale(1)" will be used as the 'to' value, and animation will proceed using the rule above. Similarly, if the 'from' transform is "none" and the 'to' transform is "scale(2) rotate(50deg)" then the animation will execute as if the 'from' value is "scale(1) rotate(0)".

      The identity functions are translate(0), translate3d(0, 0, 0), translateX(0), translateY(0), translateZ(0), scale(1), scale3d(1, 1, 1), scaleX(1), scaleY(1), scaleZ(1), rotate(0), rotate3d(1, 1, 1, 0), rotateX(0), rotateY(0), rotateZ(0), skewX(0), skewY(0), matrix(1, 0, 0, 1, 0, 0) and matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1).

  • If both the 'from' and 'to' transforms have the same number of transform functions and corresponding functions in each transform list are of the same type:
    • Each transform function is animated with its corresponding destination function in isolation using the rules described above. The individual values are then applied as a list to produce resulting transform value.
  • Otherwise:
    • The transform function lists are each converted into the equivalent matrix3d value and animation proceeds using the rule for a single function above.

10 DOM Interfaces

This section describes the interfaces and functionality added to the DOM to support runtime access to the functionality described above.

10.1 10.1 CSSMatrix

Interface CSSMatrix

The CSSMatrix interface represents a 4x4 homogeneous matrix.

IDL Definition
  interface CSSMatrix {
      attribute float m11;
      attribute float m12;
      attribute float m13;
      attribute float m14;
      attribute float m21;
      attribute float m22;
      attribute float m23;
      attribute float m24;
      attribute float m31;
      attribute float m32;
      attribute float m33;
      attribute float m34;
      attribute float m41;
      attribute float m42;
      attribute float m43;
      attribute float m44;

      void        setMatrixValue(in DOMString string) raises(DOMException);
      CSSMatrix   multiply(in CSSMatrix secondMatrix);
      CSSMatrix   inverse() raises(DOMException);
      CSSMatrix   translate(in float x, in float y, in float z);
      CSSMatrix   scale(in float scaleX, in float scaleY, in float scaleZ);
      CSSMatrix   rotate(in float rotX, in float rotY, in float rotZ);
      CSSMatrix   rotateAxisAngle(in float x, in float y, in float z, in float angle);
  };

Attributes
m11-m44 of type float
Each of these attributes represents one of the values in the 4x4 matrix. For instance m12 represents the value in the 2nd column of the first row.
Methods
setMatrixValue
The setMatrixValue method replaces the existing matrix with one computed from parsing the passed string as though it had been assigned to the transform property in a CSS style rule.
Parameters
string of type DOMString
The string to parse.
No Return Value
Exceptions
SYNTAX_ERR
Thrown when the provided string can not be parsed into a CSSMatrix.
multiply
The multiply method returns a new CSSMatrix which is the result of this matrix multiplied by the passed matrix, with the passed matrix to the right. This matrix is not modified.
Parameters
secondMatrix of type CSSMatrix
The matrix to multipy.
Return Value
CSSMatrix
The result matrix.
No Exceptions
inverse
The inverse method returns a new matrix which is the inverse of this matrix. This matrix is not modified.
No Parameters
Return Value
CSSMatrix
The inverted matrix.
Exceptions
NOT_SUPPORTED_ERROR
Thrown when the CSSMatrix can not be inverted.
translate
The translate method returns a new matrix which is this matrix post multiplied by a translation matrix containing the passed values. If the z component is undefined, a 0 value is used in its place. This matrix is not modified.
Parameters
x of type float
The X component of the translation value.
y of type float
The Y component of the translation value.
z of type float
The (optional) Z component of the translation value.
Return Value
CSSMatrix
The result matrix.
No Exceptions
scale
The scale method returns a new matrix which is this matrix post multiplied by a scale matrix containing the passed values. If the z component is undefined, a 1 value is used in its place. If the y component is undefined, the x component value is used in its place. This matrix is not modified.
Parameters
scaleX of type float
The X component of the scale value.
scaleY of type float
The (optional) Y component of the scale value.
scaleZ of type float
The (optional) Z component of the scale value.
Return Value
CSSMatrix
The result matrix.
No Exceptions
rotate
The rotate method returns a new matrix which is this matrix post multiplied by each of 3 rotation matrices about the major axes, first X, then Y, then Z. If the y and z components are undefined, the x value is used to rotate the object about the z axis, as though the vector (0,0,x) were passed. All rotation values are in degrees. This matrix is not modified.
Parameters
rotX of type float
The X component of the rotation value, or the Z component if the rotY and rotZ parameters are undefined.
rotY of type float
The (optional) Y component of the rotation value.
rotZ of type float
The (optional) Z component of the rotation value.
Return Value
CSSMatrix
The result matrix.
No Exceptions
rotateAxisAngle
The rotateAxisAngle method returns a new matrix which is this matrix post multiplied by a rotation matrix with the given axis and angle. The right-hand rule is used to determine the direction of rotation. All rotation values are in degrees. This matrix is not modified.
Parameters
x of type float
The X component of the axis vector.
y of type float
The Y component of the axis vector.
z of type float
The Z component of the axis vector.
angle of type float
The angle of rotation about the axis vector, in degrees.
Return Value
CSSMatrix
The result matrix.
No Exceptions

10.2 10.2 CSSTransformValue

Interface CSSTransformValue

The CSSTransformValue interface represents one transform function in the transform property. The operationType defines which operation is represented. The object also contains a list of values, which are the parameters of the function, in the same order in which they appear in the transform functions.

IDL Definition
  interface CSSTransformValue : CSSValueList {

      // 2D OperationTypes
      const unsigned short CSS_TRANSLATE   = 1;
      const unsigned short CSS_TRANSLATEX  = 2;
      const unsigned short CSS_TRANSLATEY  = 3;
      const unsigned short CSS_ROTATE      = 4;
      const unsigned short CSS_SCALE       = 5;
      const unsigned short CSS_SCALEX      = 6;
      const unsigned short CSS_SCALEY      = 7;
      const unsigned short CSS_SKEW        = 8;
      const unsigned short CSS_SKEWX       = 9;
      const unsigned short CSS_SKEWY       = 10;
      const unsigned short CSS_MATRIX      = 11;

      // 3D OperationTypes
      const unsigned short CSS_TRANSLATEZ  = 12;
      const unsigned short CSS_TRANSLATE3D = 13;
      const unsigned short CSS_ROTATEX     = 14;
      const unsigned short CSS_ROTATEY     = 15;
      const unsigned short CSS_ROTATEZ     = 16;
      const unsigned short CSS_ROTATE3D    = 17;
      const unsigned short CSS_SCALEZ      = 18;
      const unsigned short CSS_SCALE3D     = 19;
      const unsigned short CSS_PERSPECTIVE = 20;
      const unsigned short CSS_MATRIX3D    = 21;

      attribute unsigned short operationType;

      CSSMatrix getCSSMatrix() raises(DOMException);
  };
Attributes
operationType of type unsigned short
One of the listed operation types.
Methods
getCSSMatrix
The getCSSMatrix method returns a CSSMatrix object representing this transform.
No Parameters
Return Value
CSSMatrix
The result matrix.
Exceptions
NOT_SUPPORTED_ERROR
Thrown when the CSSTranformValue can not be converted into a CSSMatrix, such as when the CSSTransformValue contains percentage units and is being called on an object with unknown dimensions.

In addition to the interfaces listed above, the getComputedStyle method of the Window object has been updated. The transform property of the style object returned by getComputedStyle contains a single CSSTransformValue with a type of CSS_MATRIX3D. The 16 parameters represent the 4x4 matrix that is the result of applying the individual functions listed in the transform property.

11 References

Normative references

Other references

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
backface-visibility | visible | hidden | visible | block-level and inline-level elements | no | N/A | visual
perspective | none | <number> | none | block-level and inline-level elements | no | N/A | visual
perspective-origin | [ [ <percentage> | <length> | left | center | right ] [ <percentage> | <length> | top | center | bottom ]? ] | [ [ left | center | right ] || [ top | center | bottom ] ] | 50% 50% | block-level and inline-level elements | no | refer to the size of the box itself | visual
transform | none | <transform-function> [ <transform-function> ]* | none | block-level and inline-level elements | no | refer to the size of the element's box | visual
transform-origin | [ [ [ <percentage> | <length> | left | center | right ] [ <percentage> | <length> | top | center | bottom ]? ] <length> ] | [ [ [ left | center | right ] || [ top | center | bottom ] ] <length> ] | 50% 50% 0 | block-level and inline-level elements | no | refer to the size of the element's box | visual
transform-style | flat | preserve-3d | flat | block-level and inline-level elements | no | N/A | visual

Index

  • backface-visibility, 7
  • perspective, 5
  • perspective-origin, 6
  • transform, 2
  • transform-origin, 3
  • transform-style, 4


CSS3 Animations Module

CSS Animations Module Level 3

W3C Working Draft 20 March 2009

This version:
http://www.w3.org/TR/2009/WD-css3-animations-20090320
Latest version:
http://www.w3.org/TR/css3-animations
Previous version:
none
Editors:
Dean Jackson (Apple Inc)
David Hyatt (Apple Inc)
Chris Marrin (Apple Inc)

Copyright © 2009 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

CSS Animations allow an author to modify CSS property values over time.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text "css3-animations" in the subject, preferably like this: "[css3-animations] .summary of comment."

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This is the first public Working Draft of the "css3-animations" series.

Table of contents

  • 1 Introduction
  • 2 Keyframes
    • 2.1 Timing functions for keyframes
  • 3 Animations
    • 3.1 Animation behavior
    • 3.2 The 'animation-name' Property
    • 3.3 The 'animation-duration' Property
    • 3.4 The 'animation-timing-function' Property
    • 3.5 The 'animation-iteration-count' Property
    • 3.6 The 'animation-direction' Property
    • 3.7 The 'animation-play-state' Property
    • 3.8 The 'animation-delay' Property
    • 3.9 The 'animation' Shorthand Property
  • 4 Animation Events
  • 5 DOM Interfaces
  • 6 References
    • Normative references
    • Other references
  • Property index
  • Index

1 Introduction

This section is not normative.

This document introduces new CSS features to enable animation.

Animation is currently possible in languages like SVG, but no system exists for the native animation of CSS styles. This proposal introduces defined animations, which specify the values that CSS properties will take over a given time interval.

This specification is an extension to CSS Transitions [CSS3-TRANSITIONS].

2 Keyframes

In a simple transition, since both the starting value and ending value are known, a single timing function and duration determine the intermediate values of the animating property. If finer control of the intermediate values is required, keyframes can be used.

Keyframes are specified using a specialized CSS at-rule. A @keyframes rule consists of the keyword "@keyframes", followed by an identifier giving a name for the animation (which will be referenced using 'animation-name'), followed by a set of style rules (delimited by curly braces).

The keyframe selector for a keyframe style rule consists of a comma-separated list of percentage values or the keywords 'from' or 'to'. The selector is used to specify the percentage along the duration of the animation that the keyframe represents. The keyframe itself is specified by the block of property values declared on the selector. The keyword 'from' is equivalent to the value 0. The keyword 'to' is equivalent to the value 100%. Note that the percentage unit specifier must be used on percentage values. Therefore, "0" is an invalid keyframe selector.

Keyframes can be specified in any order. The selector determines the placement of the keyframe in the animation.

Every keyframe declaration must have a keyframe rule for 0% or 100%, possibly defined using "from" or "to". A keyframe declaration without these keyframe selectors is invalid and will not be available for animation.

The keyframe declaration for a keyframe rule consists of properties and values. Properties that are unable to be animated are ignored in these rules, with the exception of animation-timing-function', the behavior of which is described below.

The @keyframes rule that is used by an animation will be the last one encountered in sorted rules order that matches the name of the animation. @keyframes rules do not cascade; therefore an animation will never derive keyframes from more than one @keyframes rule.

To determine the set of keyframes, all of the values in selectors are sorted in increasing order by time. If there are any duplicates, then the last keyframe specified inside the @keyframes rule will be used to provide the keyframe information for that time. There is no cascading within a @keyframes rule if multiple keyframes specify the same keyframe selector values.

Example(s):

  @keyframes 'wobble' {

    0% {
      left: 100px;
    }

    40% {
      left: 150px;
    }

    60% {
      left: 75px;
    }

    100% {
      left: 100px;
    }

  }
Four keyframes are specified for the animation named "wobble". In the first keyframe, shown at the beginning of the animation cycle, the 'left' value of the animation is 100px. By 40% of the animation duration, 'left' value has animated to 150px. At 60% of the animation duration, the 'left' value has animated back to 75px. At the end of the animation cycle, the 'left' value has returned to 100px. The diagram below shows the state of the animation if it were given a duration of 10s.

Animations states specified by keyframes

The following is the grammar for the keyframes rule.

        keyframes-rule: '@keyframes' IDENT '{' keyframes-blocks '}';

        keyframes-blocks: [ keyframe-selectors block ]* ;

        keyframe-selectors: [ 'from' | 'to' | PERCENTAGE ] [ ',' [ 'from' | 'to' | PERCENTAGE ] ]*;

2.1 Timing functions for keyframes

A keyframe style rule may also declare the timing function that is to be used as the animation moves to the next keyframe.

Example(s):

  @keyframes 'bounce' {

    from {
      top: 100px;
      animation-timing-function: ease-out;
    }

    25% {
      top: 50px;
      animation-timing-function: ease-in;
    }

    50% {
      top: 100px;
      animation-timing-function: ease-out;
    }

    75% {
      top: 75px;
      animation-timing-function: ease-in;
    }

    to {
      top: 100px;
    }

  }
Five keyframes are specified for the animation named "bounce". Between the first and second keyframe (ie. between 0 and 25%) an "ease-out" timing function is used. Between the second and third keyframe (ie. between 25% and 50%) an "ease-in" timing function is used. And so on. The effect will appear as an element that moves up the page 50px, slowing down as it reaches its highest point then speeding up as it falls back to 100px. The second half of the animation behaves in a similar manner, but only moves the element 25px units up the page.

See the 'animation-timing-function' property for more information.

3 Animations

Animations are similar to transitions in that they change the presentational value of CSS properties over time. The principal difference is that while transitions trigger implicitly when property values change, animations are explicitly executed when the animation properties are applied. Because of this, animations require explicit values for the properties being animated. These values are specified using animation keyframes, described above.

Many aspects of the animation can be controlled, including how many times the animation iterates, whether or not it alternates between the begin and end values, and whether or not the animation should be running or paused. An animation can also delay its start time.

Example(s):

  div {
    animation-name: 'diagonal-slide';
    animation-duration: 5s;
    animation-iteration-count: 10;
  }

  @keyframes 'diagonal-slide' {

    from {
      left: 0;
      top: 0;
    }

    to {
      left: 100px;
      top: 100px;
    }

  }
This will produce an animation that moves an element from (0, 0) to (100px, 100px) over five seconds and repeats itself nine times (for a total of ten iterations).

3.1 Animation behavior

CSS Animations affect computed property values. During the execution of an animation, the computed value for a property is controlled by the animation. This overrides the value specified in the normal styling system.

In the case of multiple animations specifying behavior for the same property, the animation defined last will override the previously defined animations.

An animation does not affect the computed value before the application of the animation, before the animation delay has expired, and after the end of the animation.

Computation of animated property values

The diagram above shows how property values are computed. The intrinsic style is shown at the top of the diagram. The computed value is derived from intrinsic style at the times when an animation is not running and also when an animation is delayed (see below for specification of animation delay). During an animation, the computed style is derived from the animated value.

The start time of an animation is the latter of two moments: the time at which the style is resolved that specifies the animation, or the time the document's load event is fired. Therefore, an animation specified in the document stylesheet will begin at the document load. An animation specified on an element by modifying the style after the document has loaded will start when the style is resolved. That may be immediately in the case of a pseudo style rule such as hover, or may be when the scripting engine returns control to the browser (in the case of style applied by script).

An animation applies to an element if the element has a value for 'animation-name' that references a valid keyframes rule. Once an animation has started it continues until it ends or the 'animation-name' is removed. The values used for the keyframes and animation properties are snapshotted at the time the animation starts. Changing them during the execution of the animation has no effect. Note also, that changing the value of 'animation-name' does not necessarily restart an animation (e.g. if a list of animations are applied and one is removed from the list, only that animation will stop; The other animations will continue). In order to restart an animation, it must be removed then reapplied.

POWERED BY HeroNote

3.2 The 'animation-name' Property

The 'animation-name' property defines a list of animations that apply. Each name is used to select the keyframe at-rule that provides the property values for the animation. If the name does not match any keyframe at-rule, there are no properties to be animated and the animation will not execute. Furthermore, if the animation name is 'none' then there will be no animation. This can be used to override any animations coming from the cascade.

Name: | animation-name
Value: | none | IDENT [, none | IDENT ]*
Initial: | none
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | Same as specified value.

3.3 The 'animation-duration' Property

The 'animation-duration' property defines the length of time that an animation takes to complete one cycle.

Name: | animation-duration
Value: | <time> [, <time>]*
Initial: | 0
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | Same as specified value.

By default the value is '0', meaning that the animation cycle is immediate (i.e. there will be no animation). A negative value for animation-duration is treated as '0'.

3.4 The 'animation-timing-function' Property

The 'animation-timing-function' property describes how the animation will progress over one cycle of its duration. See the 'transition-timing-function' property [CSS3-TRANSITIONS] for a complete description of timing function calculation.

Name: | animation-timing-function
Value: | ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier(<number>, <number>, <number>, <number>) [, ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier(<number>, <number>, <number>, <number>)]*
Initial: | ease
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | Same as specified value.

For a keyframed animation, the 'animation-timing-function' applies between keyframes, not over the entire animation. For example, in the case of an ease-in-out timing function, an animation will ease in at the start of the keyframe and ease out at the end of the keyframe. A 'animation-timing-function' defined within a keyframe block applies to that keyframe, otherwise the timing function specified for the animation is used.

3.5 The 'animation-iteration-count' Property

The 'animation-iteration-count' property defines the number of times an animation cycle is played. The default value is one, meaning the animation will play from beginning to end once. A value of 'infinite' will cause the animation to repeat forever. Non-integer numbers will cause the animation to end part-way through a cycle. Negative values for 'animation-iteration-count' are treated as zero. This property is often used with an 'animation-direction' value of 'alternate', which will cause the animation to play in reverse on alternate cycles.

Name: | animation-iteration-count
Value: | infinite | <number> [, infinite | <number>]*
Initial: | 1
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | Same as specified value.

3.6 The 'animation-direction' Property

The 'animation-direction' property defines whether or not the animation should play in reverse on alternate cycles. If 'alternate' is specified, the animation cycle iterations that are odd counts are played in the normal direction, and the animation cycle iterations that are even counts are played in a reverse direction. When an animation is played in reverse the timing functions are also reversed. For example, when played in reverse an ease-in animation would appear to be an ease-out animation.

Name: | animation-direction
Value: | normal | alternate [, normal | alternate]*
Initial: | normal
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | Same as specified value.

3.7 The 'animation-play-state' Property

We are considering removing 'animation-play-state' since its behaviour can be replicated using other techniques. For example, by querying the computed style, removing the animation and then setting style.

The 'animation-play-state' property defines whether the animation is running or paused. A running animation can be paused by setting this property to 'paused'. To continue running a paused animation this property can be set to 'running'. A paused animation will continue to display the current value of the animation in a static state, as if the time of the animation is constant. When a paused animation is resumed, it restarts from the current value, not necessarily from the beginning of the animation.

Name: | animation-play-state
Value: | running | paused [, running | paused]*
Initial: | running
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | Same as specified value.

3.8 The 'animation-delay' Property

The 'animation-delay' property defines when the animation will start. It allows an animation to begin execution some time after it is applied. An 'animation-delay' value of '0' means the animation will execute as soon as it is applied. Otherwise, the value specifies an offset from the moment the animation is applied, and the animation will delay execution by that offset.

If the value for 'animation-delay' is a negative time offset then the animation will execute the moment it is applied, but will appear to have begun execution at the specified offset. That is, the animation will appear to begin part-way through its play cycle. In the case where an animation has implied starting values and a negative 'animation-delay', the starting values are taken from the moment the animation is applied.

Name: | animation-delay
Value: | <time> [, <time>]*
Initial: | 0
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | Same as specified value.

3.9 The 'animation' Shorthand Property

The 'animation' shorthand property combines six of the animation properties into a single property.

Name: | animation
Value: | [<animation-name> || <animation-duration> || <animation-timing-function> || <animation-delay> || <animation-iteration-count> || <animation-direction>] [, [<animation-name> || <animation-duration> || <animation-timing-function> || <animation-delay> || <animation-iteration-count> || <animation-direction>] ]*
Initial: | see individual properties
Applies to: | block-level and inline-level elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | Same as specified value.

4 Animation Events

Several animation related events are available through the DOM Event system. The start and end of an animation, and the end of each iteration of an animation all generate DOM events. An element can have multiple properties being animated simultaneously. This can occur either with a single animation-name value with keyframes containing multiple properties, or with multiple animation-name values. For the purposes of events, each animation-name specifies a single animation. Therefore an event will be generated for each animation-name value and not necessarily for each property being animated.

The time the animation has been running is sent with each event generated. This allows the event handler to determine the current iteration of a looping animation or the current position of an alternating animation. This time does not include any time the animation was in the paused play state.

Interface AnimationEvent

The AnimationEvent interface provides specific contextual information associated with Animation events.

IDL Definition
  interface AnimationEvent : Event {
    readonly attribute DOMString          animationName;
    readonly attribute float              elapsedTime;
    void               initAnimationEvent(in DOMString typeArg,
                                          in boolean canBubbleArg,
                                          in boolean cancelableArg,
                                          in DOMString animationNameArg,
                                          in float elapsedTimeArg);
  };
Attributes
animationName of type DOMString, readonly
The value of the animation-name property of the animation that fired the event.
elapsedTime of type float, readonly
The amount of time the animation has been running, in seconds, when this event fired, excluding any time the animation was paused. Note that this value is not affected by the value of animation-delay. For an "animationstart" event, the elapsedTime is always zero.
Methods
initAnimationEvent
The initAnimationEvent method is used to initialize the value of an AnimationEvent created through the DocumentEvent interface. This method may only be called before the AnimationEvent has been dispatched via the dispatchEvent method, though it may be called multiple times during that phase if necessary. If called multiple times, the final invocation takes precedence.
Parameters
typeArg of type DOMString
Specifies the event type.
canBubbleArg of type boolean
Specifies whether or not the event can bubble.
cancelableArg of type boolean
Specifies whether or not the event's default action can be prevented.
animationNameArg of type DOMString
Specifies the Event's animation name.
elapsedTimeArg of type float
Specifies the amount of time, in seconds, the animation has been running at the time of initialization.
No Return Value
No Exceptions

The different types of Animation events that can occur are:

animationstart
The 'animationstart' event occurs at the start of the animation
  • Bubbles: Yes
  • Cancelable: Yes
  • Context Info: animationName
animationend
The 'animationend' event occurs when the animation finishes.
  • Bubbles: Yes
  • Cancelable: Yes
  • Context Info: animationName, elapsedTime
animationiteration
The 'animationiteration' event occurs at the end of each iteration of an animation for which animation-iteration-count is greater than one. This event does not occur for animations with an iteration count of one.
  • Bubbles: Yes
  • Cancelable: Yes
  • Context Info: animationName, elapsedTime

5 DOM Interfaces

CSS animation is exposed to the CSSOM through a pair of new interfaces describing the keyframes.

Interface CSSRule

The following 2 rule types are added to the CSSRule interface. They provide identification for the new keyframe and keyframes rules.

IDL Definition
    interface CSSRule {
      ...
      const unsigned short KEYFRAMES_RULE = 7;
      const unsigned short KEYFRAME_RULE = 8;
      ...
    };
Interface CSSKeyframeRule

The CSSKeyframeRule interface represents the style rule for a single key.

IDL Definition
    interface CSSKeyframeRule : CSSRule {
        attribute DOMString keyText;
        readonly attribute CSSStyleDeclaration style;
    };

Attributes
keyText of type DOMString
This attribute represents the key as the string representation of a floating point number between 0 and 1. If the value in the CSS style is from this value will be 0, and if the value in the CSS style is to this value will be 1.
style of type CSSStyleDeclaration
This attribute represents the style associated with this keyframe.
No Methods
Interface CSSKeyframesRule

The CSSKeyframesRule interface represents a complete set of keyframes for a single animation.

IDL Definition
    interface CSSKeyframesRule : CSSRule {
        attribute          DOMString   name;
        readonly attribute CSSRuleList cssRules;

        void               insertRule(in DOMString rule);
        void               deleteRule(in DOMString key);
        CSSKeyframeRule    findRule(in DOMString key);
    };

Attributes
name of type DOMString
This attribute is the name of the keyframes, used by the animation-name property.
cssRules of type CSSRuleList
This attribute gives access to the keyframes in the list.
Methods
insertRule
The insertRule method inserts the passed CSSKeyframeRule into the list at the passed key.
Parameters
rule of type DOMString
The rule to be inserted, expressed in the same syntax as one entry in the @keyframes rule. The key is included in the rule string, which described the point at which the rule should be inserted. If a rule with the same key already exists in the list, it is replaced with this rule.
No Return Value
No Exceptions
deleteRule
The deleteRule method deletes the CSSKeyframeRule with the passed key. If a rule with this key does not exist, the method does nothing.
Parameters
key of type DOMString
The key which describes the rule to be deleted. The key must resolve to a number between 0 and 1, or the rule is ignored.
No Return Value
No Exceptions
findRule
The findRule method returns the rule with a key matching the passed key. If no such rule exists, a null value is returned.
Parameters
key of type DOMString
The key which described the rule to find. The key must resolve to a number between 0 and 1, or the rule is ignored.
Return Value
CSSKeyframeRule
The found rule.
No Exceptions

6 References

Normative references

[CSS3-TRANSITIONS]
Dean Jackson; David Hyatt; Chris Marrin. CSS Transitions Module Level 3. 20 March 2009. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2009/WD-css3-transitions-20090320

Other references

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
animation | [<animation-name> || <animation-duration> || <animation-timing-function> || <animation-delay> || <animation-iteration-count> || <animation-direction>] [, [<animation-name> || <animation-duration> || <animation-timing-function> || <animation-delay> || <animation-iteration-count> || <animation-direction>] ]* | see individual properties | block-level and inline-level elements | no | N/A | visual
animation-delay | <time> [, <time>]* | 0 | block-level and inline-level elements | no | N/A | visual
animation-direction | normal | alternate [, normal | alternate]* | normal | block-level and inline-level elements | no | N/A | visual
animation-duration | <time> [, <time>]* | 0 | block-level and inline-level elements | no | N/A | visual
animation-iteration-count | infinite | <number> [, infinite | <number>]* | 1 | block-level and inline-level elements | no | N/A | visual
animation-name | none | IDENT [, none | IDENT ]* | none | block-level and inline-level elements | no | N/A | visual
animation-play-state | running | paused [, running | paused]* | running | block-level and inline-level elements | no | N/A | visual
animation-timing-function | ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier(<number>, <number>, <number>, <number>) [, ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier(<number>, <number>, <number>, <number>)]* | ease | block-level and inline-level elements | no | N/A | visual

Index

  • animation, 3.9
  • animation-delay, 3.8
  • animation-direction, 3.6
  • animation-duration, 3.3
  • animation-iteration-count, 3.5
  • animation-name, 3.2
  • animation-play-state, 3.7
  • animation-timing-function, 3.4


CSS3 Backgrounds and Borders Module

CSS Backgrounds and Borders Module Level 3

W3C Working Draft 12 June 2010

This version:
http://www.w3.org/TR/2010/WD-css3-background-20100612
Latest version:
http://www.w3.org/TR/css3-background/
Previous versions:
http://www.w3.org/TR/2009/CR-css3-background-20091217
Editors:
Bert Bos (W3C)
Elika J. Etemad (Invited Expert)
Brad Kemper (Invited Expert)

Copyright © 2010 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

CSS is a language for describing the rendering of structured documents (such as HTML and XML) on screen, on paper, in speech, etc. This draft contains the features of CSS level 3 relating to borders and backgrounds. It includes and extends the functionality of CSS level 2 [CSS21], which builds on CSS level 1 [CSS1]. The main extensions compared to level 2 are borders consisting of images, boxes with multiple backgrounds, boxes with rounded corners and boxes with shadows.

This module replaces two earlier drafts: CSS3 Backgrounds and CSS3 Border.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css3-background” in the subject, preferably like this: “[css3-background] …summary of comment…”

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

The following features are at-risk and may be dropped at the end of the CR period if there has not been enough interest from implementers: ‘box-decoration-break’, ‘box-shadow’.

The CSS WG maintains an issues list for this module. A test suite for CSS Backgrounds and Borders Level 3 will be developed during the Candidate Recommendation phase.

This specification is a Last Call Working Draft. All persons are encouraged to review this document and send comments to the www-style mailing list as described above. The deadline for comments is 6 July 2010. If there's a conflict between CSS Backgrounds and Borders Level 3 and CSS 2.1, please report it to the CSS Working Group. Since these specifications are intended to be consistent with each other, conflicts indicate an error in one or both specifications. Changes since the last Candidate Recommendation are listed in the Changes section.

Table of contents

  • 1. Introduction
  • 2. Values
  • 3. Background properties
    • 3.1. Layering multiple background images
    • 3.2. The ‘background-color’ property
    • 3.3. The ‘background-image’ property
    • 3.4. The ‘background-repeat’ property
    • 3.5. The ‘background-attachment’ property
    • 3.6. The ‘background-position’ property
    • 3.7. The ‘background-clip’ property
    • 3.8. The ‘background-origin’ property
    • 3.9. The ‘background-size’ property
    • 3.10. The ‘background’ shorthand property
    • 3.11. The backgrounds of special elements
  • 4. Border properties
    • 4.1. The ‘border-color’ properties
    • 4.2. The ‘border-style’ properties
    • 4.3. The ‘border-width’ properties
    • 4.4. The ‘border-radius’ properties
      • 4.4.1. Corner Shaping
      • 4.4.2. Corner Clipping
      • 4.4.3. Color and Style Transitions
      • 4.4.4. Overlapping Curves
      • 4.4.5. Effect on Tables
    • 4.5. The border shorthand properties
  • 5. Border Images
    • 5.1. The ‘border-image-source’ property
    • 5.2. The ‘border-image-slice’ property
    • 5.3. The ‘border-image-width’ property
    • 5.4. The ‘border-image-outset’ property
    • 5.5. The ‘border-image-repeat’ property
    • 5.6. Border-image drawing process
    • 5.7. The ‘border-image’ shorthand
  • 6. Miscellaneous Effects
    • 6.1. The ‘box-decoration-break’ property
    • 6.2. The ‘box-shadow’ property
  • 7. Definitions
    • 7.1. Glossary
    • 7.2. Conformance
    • 7.3. Levels
      • 7.3.1. CSS Level 1
      • 7.3.2. CSS Level 2
      • 7.3.3. CSS Level 3
    • 7.4. CR exit criteria
  • 8. Changes Since the 17 December 2009 Candidate Recommendation
  • 9. Acknowledgments
  • 10. References
    • Normative references
    • Other references
  • Property index
  • Index

1. Introduction

This section is not normative.

When elements are rendered according to the CSS box model [CSS21], each element is either not displayed at all, or formatted as one or more rectangular boxes. Each box has a rectangular content area, a band of padding around the content, a border around the padding, and a margin outside the border. (The margin may actually be negative, but margins have no influence on the background and border.)

Diagram of a typical box, showing the content, padding, border and margin areas

The various areas and edges of a typical box. (This diagram is explained in the CSS2.1 Box Model chapter [CSS21].)

The properties of this module deal with the decoration of the border area and with the background of the content, padding and border areas. Additionally the box may be given a "drop-shadow" effect with the ‘box-shadow’ property.

If an element is broken into multiple boxes, ‘box-decoration-break’ defines how the borders and background are divided over the various boxes. (An element can result in more than one box if it is broken at the end of a line, at the end of a column or at the end of a page; and continued in the next line, column or page.)

The relative stacking order of backgrounds, borders, and shadows is given in this module. For how these layers interact with other rendered content, see Appendix E “Elaborate description of Stacking Contexts” in [CSS21].

2. Values

This specification follows the CSS property definition conventions from [CSS21].

<color> values are defined in CSS Color Level 3 [CSS3COLOR].

<image> values are defined by this specification as <image> = <uri>.

A future specification may expand the definition of <image> to allow other values, e.g., to define image slices.

All other values are defined in CSS Level 2 Revision 1 [CSS21].

All properties defined in this specification also accept the inherit keyword as their value, but for readability it has not been listed explicitly.

3. Background properties

Each box has a background layer that may be fully transparent (the default), or filled with a color and/or one or more images. The background properties specify what color (‘background-color’) and images (‘background-image’) to use, and how they are sized, positioned, tiled, etc.

The background properties are not inherited, but the parent box's background will shine through by default because of the initial ‘transparent’ value on ‘background-color’.

3.1. Layering multiple background images

The background of a box can have multiple layers in CSS3. The number of layers is determined by the number of comma-separated values in the ‘background-image’ property. Note that a value of ‘none’ still creates a layer.

Each of the images is sized, positioned, and tiled according to the corresponding value in the other background properties. The lists are matched up from the first value: excess values at the end are not used. If a property doesn't have enough comma-separated values to match the number of layers, the UA must calculate its used value by repeating the list of values until there are enough.

For example, this set of declarations:

background-image: url(flower.png), url(ball.png), url(grass.png);
background-position: center center, 20% 80%, top left, bottom right;
background-origin: border-box, content-box;
background-repeat: no-repeat;

has exactly the same effect as this set with the extra position dropped and the missing values for ‘background-origin’ and ‘background-repeat’ filled in (emphasized for clarity):

background-image: url(flower.png), url(ball.png), url(grass1.png);
background-position: center center, 20% 80%, top left;
background-origin: border-box, content-box, border-box;
background-repeat: no-repeat, no-repeat, no-repeat;

The first image in the list is the layer closest to the user, the next one is painted behind the first, and so on. The background color, if present, is painted below all of the other layers.

Note that the border-image properties can also define a background image, which, if present, is painted on top of the background created by the background properties.

3.2. The ‘background-color’ property

Name: | background-color
Value: | <color>
Initial: | transparent
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | the computed color(s)

This property sets the background color of an element. The color is drawn behind any background images.

Example:

h1 { background-color: #F00 } /* Sets background to red. */

The background color is clipped according to the ‘background-clip’ value associated with the bottom-most background image.

3.3. The ‘background-image’ property

Name: | background-image
Value: | <bg-image> [ , <bg-image> ]*
Initial: | none
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified, but with URIs made absolute

This property sets the background image(s) of an element. Images are drawn with the first specified one on top (closest to the user) and each subsequent image behind the previous one. Where

<bg-image> = <image> | none

A value of ‘none’ counts as an image layer but draws nothing. An image that is empty (zero width or zero height), that fails to download, or that cannot be displayed (e.g., because it is not in a supported image format) likewise counts as a layer but draws nothing.

See the section “Layering multiple background images” for how ‘background-image’ interacts with other comma-separated background properties to form each background image layer.

When setting a background image, authors should also specify a ‘background-color’ that will preserve contrast with the text for when the image is unavailable.

Some examples specifying background images:

body { background-image: url("marble.svg") }
p { background-image: none }
div { background-image: url(tl.png), url(tr.png) }

Implementations may optimize by not downloading and drawing images that are not visible (e.g., because they are behind other, fully opaque images).

3.4. The ‘background-repeat’ property

Name: | background-repeat
Value: | <repeat-style> [ , <repeat-style> ]*
Initial: | repeat
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified

Specifies how background images are tiled after they have been sized and positioned. Where

<repeat-style> = repeat-x | repeat-y | [repeat | space | round | no-repeat]{1,2}

Single values for <repeat-style> have the following meanings:

‘repeat-x’
Equivalent to ‘repeat no-repeat’.
‘repeat-y’
Equivalent to ‘no-repeat repeat’.
‘repeat’
Equivalent to ‘repeat repeat’.
‘space’
Equivalent to ‘space space’
‘round’
Equivalent to ‘round round’
‘no-repeat’
Equivalent to ‘no-repeat no-repeat’

If a <repeat-style> value has two keywords, the first one is for the horizontal direction, the second for the vertical one, as follows:

‘repeat’
The image is repeated in this direction as often as needed to cover the background painting area.
‘space’
The image is repeated as often as will fit within the background positioning area without being clipped and then the images are spaced out to fill the area. The first and last images touch the edges of the area. If the background painting area is larger than the background positioning area, then the pattern repeats to fill the background painting area. The value of ‘background-position’ for this direction is ignored, unless there is not enough space for two copies of the image in this direction, in which case only one image is placed and ‘background-position’ determines its position in this direction.
‘round’
The image is repeated as often as will fit within the background positioning area. If it doesn't fit a whole number of times, it is rescaled so that it does. See the formula under ‘background-size’. If the background painting area is larger than the background positioning area, then the pattern repeats to fill the background painting area.
‘no-repeat’
The image is placed once and not repeated in this direction.

Unless one of the two keywords is ‘no-repeat’, the whole background painting area will be tiled, i.e., not just one vertical strip and one horizontal strip.

Example(s):

body {
  background: white url("pendant.png");
  background-repeat: repeat-y;
  background-position: center;
}

A centered background image, with copies repeated up and down the border, padding and content areas.

The effect of ‘repeat-y’: One copy of the background image is centered, and other copies are put above and below it to make a vertical band behind the element.

Example(s):

body {
  background-image: url(dot.png) white;
  background-repeat: space
}

Image of an element with a dotted background

The effect of ‘space’: the image of a dot is tiled to cover the whole background and the images are equally spaced.

See the section “Layering multiple background images” for how ‘background-repeat’ interacts with other comma-separated background properties to form each background image layer.

3.5. The ‘background-attachment’ property

Name: | background-attachment
Value: | <attachment> [ , <attachment> ]*
Initial: | scroll
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified

If background images are specified, this property specifies whether they are fixed with regard to the viewport (‘fixed’) or scroll along with the element (‘scroll’) or its contents (‘local’). The property's value is given as a comma-separated list of <attachment> keywords where

<attachment> = scroll | fixed | local
fixed
The background is fixed with regard to the viewport. In paged media where there is no viewport, a ‘fixed’ background is fixed with respect to the page box. >Note that there is only one viewport per view. Even if an element has a scrolling mechanism (see the ‘overflow’ property [CSS21]), a ‘fixed’ background doesn't move with the element.
local
The background is fixed with regard to the element's contents: if the element has a scrolling mechanism, the background scrolls with the element's contents. In this case, the background behind the element's border (if any) scrolls as well, even though the border itself does not scroll with the contents. The UA may, however, treat the ‘border-box’ value of ‘background-clip’ as ‘padding-box’ in cases where ‘background-attachment’ is ‘local’ and the contents of the element scroll.
scroll
The background is fixed with regard to the element itself and does not scroll with its contents. (It is effectively attached to the element's border.)

Even if the image is fixed, it is still only visible when it is in the background painting area of the element or otherwise unclipped. (See “The backgrounds of special elements” for the cases when background images are not clipped.) Thus, unless the image is tiled, it may be invisible.

This example creates an infinite vertical band that remains “glued” to the viewport when the element is scrolled.

body {
  background: red url("pendant.gif");
  background-repeat: repeat-y;
  background-attachment: fixed;
}

User agents that do not support ‘fixed’ backgrounds (for example due to limitations of the hardware platform) should ignore declarations with the keyword ‘fixed’. For example:

body {
   /* For all UAs: */
   background: white url(paper.png) scroll;
   /* For UAs that do fixed backgrounds: */
   background: white url(ledger.png) fixed;
}
h1 {
   /* For all UAs: */
   background: silver;
   /* For UAs that do fixed backgrounds: */
   background: url(stripe.png) fixed, white url(ledger.png) fixed;
}

See the section “Layering multiple background images” for how ‘background-attachment’ interacts with other comma-separated background properties to form each background image layer.

3.6. The ‘background-position’ property

Name: | background-position
Value: | <bg-position> [ , <bg-position> ]*
Initial: | 0% 0%
Applies to: | all elements
Inherited: | no
Percentages: | refer to size of background positioning area minus size of background image; see text
Media: | visual
Computed value: | If one or two values are specified, for a <length> the absolute length, otherwise a percentage. If three or four values are specified, two pairs of a keyword plus a length or percentage.

If background images have been specified, this property specifies their initial position (after any resizing) within their corresponding background positioning area.

Where

<bg-position> = [
  [ top | bottom ]
|
  [ <percentage> | <length> | left | center | right ]
  [ <percentage> | <length> | top | center | bottom ]?
|
  [ center | [ left | right ] [ <percentage> | <length> ]? ] &&
  [ center | [ top | bottom ] [ <percentage> | <length> ]? ]
]

If only one value is specified, the second value is assumed to be ‘center’. If two values are given and at least one value is not a keyword, then the first value represents the horizontal position (or offset) and the second represents the vertical position (or offset). <percentage> and <length> values here represent an offset of the top left corner of the background image from the top left corner of the background positioning area.

If three or four values are given, then each <percentage> or<length> represents an offset and must be preceded by a keyword, which specifies from which edge the offset is given. For example, ‘background-position: bottom 10px right 20px’ represents a ‘10px’ vertical offset up from the bottom edge and a ‘20px’ horizontal offset leftward from the right edge. If three values are given, the missing offset is assumed to be zero.

Positive values represent an offset inward from the edge of the background positioning area. Negative values represent an offset outward from the edge of the background positioning area.

The following declarations give the stated (horizontal, vertical) offsets from the top left corner:

 background-position: left 10px top 15px;   /* 10px, 15px */
 background-position: left      top     ;   /*  0px,  0px */
 background-position:      10px     15px;   /* 10px, 15px */
 background-position: left          15px;   /*  0px, 15px */
 background-position:      10px top     ;   /* 10px,  0px */
 background-position: left      top 15px;   /*  0px, 15px */
 background-position: left 10px top     ;   /* 10px,  0px */
<percentage>

A percentage for the horizontal offset is relative to (width of background positioning area - width of background image). A percentage for the vertical offset is relative to (height of background positioning area - height of background image), where the size of the image is the size given by ‘background-size’.

For example, with a value pair of ‘0% 0%’, the upper left corner of the image is aligned with the upper left corner of, usually, the box's padding edge. A value pair of ‘100% 100%’ places the lower right corner of the image in the lower right corner of the area. With a value pair of ‘75% 50%’, the point 75% across and 50% down the image is to be placed at the point 75% across and 50% down the area.

Diagram of image position within element

Diagram of the meaning of ‘background-position: 75% 50%’.

<length>
A length value gives a fixed length as the offset. For example, with a value pair of ‘2cm 1cm’, the upper left corner of the image is placed 2cm to the right and 1cm below the upper left corner of the background positioning area.
‘top’
Equivalent to ‘0%’ for the vertical position if one or two values are given, otherwise specifies the top edge as the origin for the next offset.
‘right’
Equivalent to ‘100%’ for the horizontal position if one or two values are given, otherwise specifies the right edge as the origin for the next offset.
‘bottom’
Equivalent to ‘100%’ for the vertical position if one or two values are given, otherwise specifies the bottom edge as the origin for the next offset.
‘left’
Equivalent to ‘0%’ for the horizontal position if one or two values are given, otherwise specifies the left edge as the origin for the next offset.
‘center’
Equivalent to ‘50%’ (‘left 50%’) for the horizontal position if the horizontal position is not otherwise specified, or ‘50%’ (‘top 50%’) for the vertical position if it is.

The following ‘background’ shorthand declarations use keywords to set ‘background-position’ to the stated percentage values.

body { background: url("banner.jpeg") right top }    /* 100%   0% */
body { background: url("banner.jpeg") top center }   /*  50%   0% */
body { background: url("banner.jpeg") center }       /*  50%  50% */
body { background: url("banner.jpeg") bottom }       /*  50% 100% */

In the example below, the (single) image is placed in the lower-right corner of the viewport.

body {
  background-image: url("logo.png");
  background-attachment: fixed;
  background-position: 100% 100%;
  background-repeat: no-repeat;
}

Background positions can also be relative to other corners than the top left. E.g., the following puts the background image 10px from the bottom and 3em from the right:

background-position: right 3em bottom 10px

See the section “Layering multiple background images” for how ‘background-position’ interacts with other comma-separated background properties to form each background image layer.

3.7. The ‘background-clip’ property

Name: | background-clip
Value: | <box> [ , <box> ]*
Initial: | border-box
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | same as specified value

Determines the background painting area. The syntax of the property is given with

<box> = border-box | padding-box | content-box

Values have the following meanings:

‘border-box’
The background is painted within (clipped to) the border box.
‘padding-box’
The background is painted within (clipped to) the padding box.
‘content-box’
The background is painted within (clipped to) the content box.

Note that the root element has a different background painting area. See “The backgrounds of special elements.”

Note that the background is always drawn behind the border, if any. See “Elaborate description of Stacking Contexts” in [CSS21].

See the section “Layering multiple background images” for how ‘background-clip’ interacts with other comma-separated background properties to form each background image layer.

3.8. The ‘background-origin’ property

Name: | background-origin
Value: | <box> [ , <box> ]*
Initial: | padding-box
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | same as specified value

For elements rendered as a single box, specifies the background positioning area. For elements rendered as multiple boxes (e.g., inline boxes on several lines, boxes on several pages) specifies which boxes ‘box-decoration-break’ operates on to determine the background positioning area(s).

‘padding-box’
The position is relative to the padding box. (For single boxes ‘0 0’ is the upper left corner of the padding edge, ‘100% 100%’ is the lower right corner.)
‘border-box’
The position is relative to the border box.
‘content-box’
The position is relative to the content box.

If the ‘background-attachment’ value for this image is ‘fixed’, then this property has no effect: in this case the background positioning area is the initial containing block [CSS21].

Note that if ‘background-clip’ is ‘padding-box’, ‘background-origin’ is ‘border-box’, ‘background-position’ is ‘top left’ (the initial value), and the element has a non-zero border, then the top and left of the background image will be clipped.

See the section “Layering multiple background images” for how ‘background-clip’ interacts with other comma-separated background properties to form each background image layer.

3.9. The ‘background-size’ property

Name: | background-size
Value: | <bg-size> [ , <bg-size> ]*
Initial: | auto
Applies to: | all elements
Inherited: | no
Percentages: | see text
Media: | visual
Computed value: | for <length> the absolute value, otherwise as specified

Specifies the size of the background images. Where

<bg-size> = [ <length> | <percentage> | auto ]{1,2} | cover | contain

Values have the following meanings:

‘contain’
Scale the image, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area.
‘cover’
Scale the image, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.
[ <length> | <percentage> | auto ]{1,2}

The first value gives the width of the corresponding image, the second value its height. If only one value is given the second is assumed to be ‘auto’.

A percentage is relative to the background positioning area.

An ‘auto’ value for one dimension is resolved by using the image's intrinsic ratio and the size of the other dimension, or failing that, using the image's intrinsic size, or failing that, treating it as 100%.

If both values are ‘auto’ then the intrinsic width and/or height of the image should be used, if any. If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for ‘contain’.

Negative values are not allowed.

Here are some examples. The first example stretches the background image independently in both dimensions to completely cover the content area:

div {
    background-image: url(plasma.png);
    background-repeat: no-repeat;
    background-size: 100% 100%;
    background-origin: content-box }

The second example stretches the image so that exactly two copies fit horizontally. The aspect ratio is preserved:

p {
    background-image: url(tubes.png);
    background-size: 50% auto;
    background-origin: border-box }

This example forces the background image to be 15 by 15 pixels:

para {
    background-size: 15px 15px;
    background-image: url(tile.png)}

This example uses the image's intrinsic size. Note that this is the only possible behavior in CSS level 1 and 2.

body {
    background-size: auto;            /* default */
    background-image: url(flower.png) }

The following example rounds the height of the image to 25%, down from the specified value of 30%. At 30%, three images would fit entirely and a fourth only partially. After rounding, four images fit. The width of the image is 20% of the background area width and is not rounded.

p {
    background-image: url(chain.png);
    background-repeat: no-repeat round;
    background-size: 20% 30% }

If ‘background-repeat’ is ‘round’ for one (or both) dimensions, there is a second step. The UA must scale the image in that dimension (or both dimensions) so that it fits a whole number of times in the background positioning area. In the case of the width (height is analogous):

If X ≠ 0 is the width of the image after step one and W is the width of the background positioning area, then the rounded width X' = W / round(W / X) where round() is a function that returns the nearest natural number (integer greater than zero).

This will round to the nearest whole number of tiles, which keeps closer to the intended size and, in the case where one dimension is fixed (e.g. in ‘border-image’), keeps the image closer to the intended aspect ratio. This is almost certainly the best solution for vector images and high-resolution raster images. However, if the given image is a low-resolution raster image, it will require interpolating pixels, which can look bad. See Rounding Extremes for illustrations. The workaround is to specify a higher-resolution image (e.g. by shrinking with ‘background-size’ or ‘border-image-width’). Possible spec solutions include introducing a separate keyword that always scales down, or to change the algorithm so that we force scaling down when interpolation would be required for scaling up. The CSSWG is looking for feedback on this issue.

If ‘background-repeat’ is ‘round’ for one dimension only and if ‘background-size’ is ‘auto’ for the other dimension, then there is a third step: that other dimension is scaled so that the original aspect ratio is restored.

In this example the background image is shown at its intrinsic size:

div {
  background-image: url(image1.png);
  background-repeat: repeat;         /* default */
  background-size: auto }            /* default */

In the following example, the background is shown with a width of 3em and its height is scaled proportionally to keep the original aspect ratio:

div {
  background-image: url(image2.png);
  background-repeat: repeat;         /* default */
  background-size: 3em }             /* = '3em auto' */

In the following example, the background is shown with a width of 3em or slightly smaller, so that it fits a whole number of times in the width of the background. The height is scaled proportionally to keep the original aspect ratio:

div {
  background-image: url(image3.png);
  background-repeat: round repeat;
  background-size: 3em auto }

In the following example, the background image is shown with a width of 3em and a height that is either the height corresponding to that width at the original aspect ratio or slightly less:

div {
  background-image: url(image4.png);
  background-repeat: repeat round;
  background-size: 3em auto }

In the following example, the background image is shown with a height of 4em or slightly less, so that it fits a whole number of times in the background height. The width is the width that correspond to a 4em height at the original aspect ratio or slightly less:

div {
  background-image: url(image5.png);
  background-repeat: round;
  background-size: auto 4em }

If the background image's width or height resolves to zero, this causes the image not to be displayed. (The effect is the same as if it had been a transparent image.)

See the section “Layering multiple background images” for how ‘background-clip’ interacts with other comma-separated background properties to form each background image layer.

3.10. The ‘background’ shorthand property

Name: | background
Value: | [ <bg-layer> , ]* <final-bg-layer>
Initial: | see individual properties
Applies to: | all elements
Inherited: | no
Percentages: | see individual properties
Media: | visual
Computed value: | see individual properties

Where

<bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2}
<final-bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2} || <'background-color'>

Note that a color is permitted in <final-bg-layer>, but not in <bg-layer>.

The ‘background’ property is a shorthand property for setting most background properties at the same place in the style sheet. Given a valid declaration, the shorthand first sets each of ‘background-color’, ‘background-position’, ‘background-size’, ‘background-repeat’, ‘background-origin’, ‘background-clip’, ‘background-attachment’ and ‘background-image’ to its initial value, then assigns explicit values given in the declaration.

If one <box> value is present then it sets both ‘background-origin’ and ‘background-clip’ to that value. If two values are present, then the first sets ‘background-origin’ and the second ‘background-clip’.

Examples:

In the first rule of the following example, only a value for ‘background-color’ has been given and the other individual properties are set to their initial values. In the second rule, many individual properties have been specified.

body { background: red }
p { background: 40% url("chess.png") / 10em gray
       round fixed border-box; }

The first rule is equivalent to:

body {
    background-color: red;
    background-position: 0% 0%;
    background-size: auto auto;
    background-repeat: repeat repeat;
    background-clip: border-box;
    background-origin: padding-box;
    background-attachment: scroll;
    background-image: none }

The second is equivalent to:

p {
    background-color: gray;
    background-position: 40% 50%;
    background-size: 10em 10em;
    background-repeat: round round;
    background-clip: border-box;
    background-origin: border-box;
    background-attachment: fixed;
    background-image: url(chess.png) }

The following example shows how a both a background color (#CCC) and a background image (url(metal.jpg)) are set. The image is rescaled to the full width of the element:

E { background: #CCC top left url("metal.jpg") / 100% auto no-repeat}

Another example shows equivalence:

div { background: padding-box url(paper.jpg) white center }
div {
    background-color: white;
    background-image: url(paper.jpg);
    background-repeat: repeat;
    background-attachment: scroll;
    background-position: center;
    background-clip: padding-box;
    background-origin: padding-box;
    background-size: auto auto }

The following declaration with multiple, comma-separated values

background: url(a.png) top left no-repeat,
            url(b.png) center / 100% 100% no-repeat,
            url(c.png) white;

is equivalent to

background-image:      url(a.png),  url(b.png),          url(c.png);
background-position:   top left,    center,              top left;
background-repeat:     no-repeat,   no-repeat no-repeat, repeat;
background-clip:       border-box,  border-box,          border-box;
background-origin:     padding-box, padding-box,         padding-box;
background-size:       auto auto,   100% 100%,           auto auto;
background-attachment: scroll,      scroll,              scroll;
background-color:      white;

Note that ‘background: url(foo) white’ and ‘background: url(foo), white’ have the same effect.

3.11. The backgrounds of special elements

The background of the root element becomes the background of the canvas and its background painting area extends to cover the entire canvas, although any images are sized and positioned relative to the root element as if they were painted for that element alone. (In other words, the background positioning area is determined as for the root element.) If the root's ‘background-color’ value is ‘transparent’, the canvas's background color is UA dependent. The root element does not paint this background again, i.e., the used value of its background is transparent.

For documents whose root element is an HTML HTML element [HTML401] or an XHTML html element [XHTML11]: if the computed value of ‘background-image’ on the root element is ‘none’ and its ‘background-color’ is ‘transparent’, user agents must instead propagate the computed values of the background properties from that element's first HTML BODY or XHTML body child element. The used values of that BODY element's background properties are their initial values, and the propagated values are treated as if they were specified on the root element. It is recommended that authors of HTML documents specify the canvas background for the BODY element rather than the HTML element.

According to these rules, the canvas underlying the following HTML document will have a “marble” background:

<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.0//EN'
  >
<html>
  <head>
    <title>Setting the canvas background</title>
    <style type="text/css">
       body { background: url("http://example.org/marble.png") }
    </style>
  </head>
  <body>
    <p>My background is marble.</p>
  </body>
</html>

The ‘::first-line’ pseudo-element is like an inline-level element for the purposes of the background (see section 5.12.1 of [CSS21]). That means, e.g., that in a left-justified first line, the background does not necessarily extend all the way to the right margin.

4. Border properties

The border can either be a predefined style (solid line, double line, dotted line, pseudo-3D border, etc.) or it can be an image. In the former case, various properties define the style (‘border-style’), color (‘border-color’), and thickness (‘border-width’) of the border.

4.1. The ‘border-color’ properties

Name: | border-top-color , border-right-color, border-bottom-color, border-left-color
Value: | <color>
Initial: | currentcolor
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | the computed color
Name: | border-color
Value: | <color>{1,4}
Initial: | (see individual properties)
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | see individual properties

These properties set the foreground color of the border specified by the border-style properties.

‘Border-color’ is a shorthand for the four ‘border-*-color’ properties. The four values set the top, right, bottom and left border, respectively. A missing left is the same as right, a missing bottom is the same as top, and a missing right is also the same as top.

4.2. The ‘border-style’ properties

Name: | border-top-style, border-right-style, border-bottom-style, border-left-style
Value: | <border-style>
Initial: | none
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified value
Name: | border-style
Value: | <border-style>{1,4}
Initial: | (see individual properties)
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | see individual properties

These properties set the style of the border, unless there is a border image

‘Border-style’ is a shorthand for the other four. Its four values set the top, right, bottom and left border respectively. A missing left is the same as right, a missing bottom is the same as top, and a missing right is also the same as top.

Where

<border-style> = none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset

Values have the following meanings:

‘none’
No border. Color and width are ignored (i.e., the border has width 0, unless the border is an image, see ‘background-image’
‘hidden’
Same as ‘none’, but has different behavior in the border conflict resolution rules for border-collapsed tables [CSS21].
‘dotted’
A series of round dots.
‘dashed’
A series of square-ended dashes.
‘solid’
A single line segment.
‘double’
Two parallel solid lines with some space between them. (The thickness of the lines is not specified, but the sum of the lines and the space must equal ‘border-width’.)
‘groove’
Looks as if it were carved in the canvas. (This is typically achieved by creating a “shadow” from two colors that are slightly lighter and darker than the ‘border-color’.)
‘ridge’
Looks as if it were coming out of the canvas.
‘inset’
Looks as if the content on the inside of the border is sunken into the canvas. Treated as ‘ridge’ in border-collapsed tables. [CSS21]
‘outset’
Looks as if the content on the inside of the border is coming out of the canvas. Treated as ‘groove’ in border-collapsed tables. [CSS21]

Borders are drawn in front of the element's background, but behind the element's content (in case it overlaps).

Examples of border styles

Example renderings of the predefined border styles.

Note: There is no control over the spacing of the dots and dashes, nor over the length of the dashes. Implementations are encouraged to choose a spacing that makes the corners symmetrical.

Note: This specification does not define how borders of different styles should be joined in the corner. Also note that rounded corners may cause the corners and the contents to overlap, if the padding is less than the radius of the corner.

4.3. The ‘border-width’ properties

Name: | border-top-width, border-right-width, border-bottom-width, border-left-width
Value: | <border-width>
Initial: | medium
Applies to: | all elements
Inherited: | no
Percentages: | width* of containing block
Media: | visual
Computed value: | absolute length; ‘0’ if the border style is ‘none’ or ‘hidden’
*) if the containing block has a horizontal text mode, otherwise the height
Name: | border-width
Value: | <border-width>{1,4}
Initial: | (see individual properties)
Applies to: | all elements
Inherited: | no
Percentages: | see individual properties
Media: | visual
Computed value: | see individual properties

These properties set the thickness of the border. Where

<border-width> = <length> | thin | medium | thick

The <length> may not be negative. The lengths corresponding to ‘thin’, ‘medium’ and ‘thick’ are not specified, but the values are constant throughout a document and thin ≤ medium ≤ thick. A UA could, e.g., make the thickness depend on the ‘medium’ font size: one choice might be 1, 3 & 5px when the ‘medium’ font size is 17px or less.

POWERED BY HeroNote

‘Border-width’ is a shorthand that sets the four ‘border-*-width’ properties. If it has four values, they set top, right, bottom and left in that order. If left is missing, it is the same as right; if bottom is missing, it is the same as top; if right is missing, it is the same as top.

Note that the initial width is ‘medium’, but the initial style is ‘none’ and therefore the used width is 0.

When the used width of the border is 0, we say that the border is absent.

4.4. The ‘border-radius’ properties

Name: | border-top-right-radius, border-bottom-right-radius, border-bottom-left-radius, border-top-left-radius
Value: | [ <length> | <percentage> ] [ <length> | <percentage> ]?
Initial: | 0
Applies to: | all elements (but see prose)
Inherited: | no
Percentages: | Refer to corresponding dimension of the border box.
Media: | visual
Computed value: | two absolute <length> or percentages
Name: | border-radius
Value: | [ <length> | <percentage> ]{1,4} [ / [ <length> | <percentage> ]{1,4} ]?
Initial: | 0
Applies to: | all elements, except table element when ‘border-collapse’ is ‘collapse’
Inherited: | no
Percentages: | Refer to corresponding dimension of the border box.
Media: | visual
Computed value: | see individual properties

The two length or percentage values of the ‘border-*-radius’ properties define the radii of a quarter ellipse that defines the shape of the corner of the outer border edge (see the diagram below). The first value is the horizontal radius, the second the vertical radius. If the second value is omitted it is copied from the first. If either length is zero, the corner is square, not rounded. Percentages for the horizontal radius refer to the width of the border box, whereas percentages for the vertical radius refer to the height of the border box.

Diagram of the inscribed ellipse

The two values of ‘border-top-left-radius: 55pt 25pt’ define the curvature of the corner.

The ‘border-radius’ shorthand sets all four ‘border-*-radius’ properties. If values are given before and after the slash, then the values before the slash set the horizontal radius and the values after the slash set the vertical radius. If there is no slash, then the values set both radii equally. The four values for each radii are given in the order top-left, top-right, bottom-right, bottom-left. If bottom-left is omitted it is the same as top-right. If bottom-right is omitted it is the same as top-left. If top-right is omitted it is the same as top-left.

border-radius: 4em;
is equivalent to
border-top-left-radius:     4em;
border-top-right-radius:    4em;
border-bottom-right-radius: 4em;
border-bottom-left-radius:  4em;
and
border-radius: 2em 1em 4em / 0.5em 3em;
is equivalent to
border-top-left-radius:     2em 0.5em;
border-top-right-radius:    1em 3em;
border-bottom-right-radius: 4em 0.5em;
border-bottom-left-radius:  1em 3em;

4.4.1. Corner Shaping

The padding edge (inner border) radius is the outer border radius minus the corresponding border thickness. In the case where this results in a negative value, the inner radius is zero. (In such cases its center might not coincide with that of the outer border curve.) Likewise the content edge radius is the padding edge radius minus the corresponding padding, or if that is negative, zero. The border and padding thicknesses in the curved region are thus interpolated from the adjoining sides, and when two adjoining borders are of different thicknesses the corner will show a smooth transition between the thicker and thinner borders.

Note that this means that if the outer curve extends past the adjacent corner's padding edge, the inner curve may not be a full quarter ellipse.

All border styles (‘solid’, ‘dotted’, ‘inset’, etc.) follow the curve of the border.

The effect of rounded corners on unequal borders

The effect of a rounded corner when the two borders it connects are of unequal thickness (left) and the effect of a rounded corner on borders that are thicker than the radius of the corner (right).

4.4.2. Corner Clipping

A box's backgrounds, but not its border-image, are clipped to the appropriate curve (as determined by ‘background-clip’). Other effects that clip to the border or padding edge (such as ‘overflow’ other than ‘visible’) also must clip to the curve. The content of replaced elements is always trimmed to the content edge curve. Also, the area outside the curve of the border edge does not accept mouse events on behalf of the element.

This example adds appropriate padding, so that the contents do not overflow the corners. Note that there is no border, but the background will still have rounded corners.

DIV {
    background: black;
    color: white;
    border-radius: 1em;
    padding: 1em }

4.4.3. Color and Style Transitions

Color and style transitions must be contained within the segment of the border that intersects the smallest rectangle that contains both border radii as well as the center of the inner curve (which may be a point representing the corner of the padding edge, if the border radii are smaller than the border-width).

The center of color and style transitions between adjoining borders is at the point on the curve that is at an angle that is proportional to the ratio of the border widths. For example, if the top and right border widths are equal, that point is at a 45° angle from the horizontal, and if the top is twice the width of the right the point is at a 30° angle from the horizontal. The line demarcating this transition is drawn between the point at that angle on the outer arc and the point at that angle on the inner arc.

It is not defined what these transitions look like, but a gradient is recommended for color transitions that don't involve dotted or dashed borders.

Illustration of the transition region on curved corners

Given these corner shapes, color and style transitions must be contained within the green region. In case D the rectangle defined by the border radii does not include the center of the inner curve (which is a sharp corner), so the transition region is expanded to include that corner. Transitions may take up the entire transition region, but are not required to: For example, a gradient color transition between two solid border styles might take up only the region bounded by the tips of the outer radii and the tips of the inner radii (represented in case D by the dark green region).

4.4.4. Overlapping Curves

Corner curves must not overlap: When the sum of any two adjacent border radii exceeds the size of the border box, UAs must proportionally reduce the used value of all border radii until none of them overlap. The algorithm for reducing radii is as follows:

Let f = min(Li/Si), where i ∈ {top, right, bottom, left}, Si is the sum of the radii of the corners on side i, and Ltop = Lbottom = the width of the box, and Lleft = Lright = the height of the box. If f < 1, then all corner radii are reduced by multiplying them by f.

Note that this formula ensures that quarter circles remain quarter circles and large radii remain larger than smaller ones, but it may reduce corners that were already small enough, which may make borders of nearby elements that should look the same look different.

If the curve interferes with UI elements such as scrollbars, the UA may further reduce the used value of the affected border radii (and only the affected border radii) as much as necessary, but no more.

The rendering of the box must be exactly the same as if the reduced border-radius values were those originally specified.

For example, the borders A and D of the figure below might be the result of

box-sizing: border-box;
width: 6em;
height: 2.5em;
border-radius: 0.5em 2em 0.5em 2em

The height (2.5em) is enough for the specified radii (0.5em plus 2.5em). However, if the height is only 2em,

box-sizing: border-box;
width: 6em;
height: 2em;
border-radius: 0.5em 2em 0.5em 2em

all corners need to be reduced by a factor 0.8 to make them fit. The used border radii thus are 0.4em (instead of 0.5em) and 1.6em (instead of 2em). See borders B and C in the figure.

[image: rectangle with two tiny rounded corners and two very large ones, on opposite corners]

These rounded corner might be the result of ‘width: 6em; height: 2.5em; border-radius: 0.5em 2em 0.5em 2em’ for A and D; and ditto but with ‘height: 2em’ for B and C.

4.4.5. Effect on Tables

The ‘border-radius’ properties do apply to ‘table’ and ‘inline-table’ elements. When ‘border-collapse’ is ‘collapse’, the UA may apply the border-radius properties to ‘table’ and ‘inline-table’ elements, but is not required to. In this case not only must the border radii of adjacent corners not intersect, but the horizontal and vertical radii of a single corner may not extend past the boundaries of the cell at that corner (i.e. the cell's other corners must not be affected by this corner's border-radius). If the computed values of the border radii would cause this effect, then the used values of all the border radii of the table must be reduced by the same factor so that the radii neither intersect nor extend past the boundaries of their respective corner cells.

The effect of border-radius on internal table elements is undefined in CSS3 Backgrounds and Borders, but may be defined in a future specification. CSS3 UAs should ignore border-radius properties applied to internal table elements when ‘border-collapse’ is ‘collapse’.

This example draws ovals of 15em wide and 10em high:

DIV.standout {
    width: 13em;
    height: 8em;
    border: solid black 1em;
    border-radius: 7.5em 5em }

4.5. The border shorthand properties

Name: | border-top, border-right, border-bottom, border-left
Value: | <border-width> || <border-style> || <color>
Initial: | See individual properties
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | see individual properties

This is a shorthand property for setting the width, style, and color of the top, right, bottom, and left border of a box. Omitted values are set to their initial values.

Name: | border
Value: | <border-width> || <border-style> || <color>
Initial: | See individual properties
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | see individual properties

The ‘border’ property is a shorthand property for setting the same width, color, and style for all four borders of a box. Unlike the shorthand ‘margin’ and ‘padding’ properties, the ‘border’ property cannot set different values on the four borders. To do so, one or more of the other border properties must be used.

The ‘border’ shorthand also resets ‘border-image’ to its initial value. It is therefore recommended that authors use the ‘border’ shorthand, rather than other shorthands or the individual properties, to override any border settings earlier in the cascade. This will ensure that ‘border-image’ has also been reset to allow the new styles to take effect.

The CSS Working Group intends for the ‘border’ shorthand to reset all border properties in future levels of CSS as well. For example, if a ‘border-characters’ property is introduced in the future to allow glyphs as borders, it will also be reset by the ‘border’ shorthand. By using the ‘border’ shorthand to reset borders, authors can be guaranteed a “blank canvas” no matter what properties are introduced in the future.

For example, the first rule below is equivalent to the set of four rules shown after it:

p { border: solid red }
p {
  border-top: solid red;
  border-right: solid red;
  border-bottom: solid red;
  border-left: solid red;
  border-image: none;
}

Since, to some extent, the properties have overlapping functionality, the order in which the rules are specified is important.

Consider this example:

blockquote {
  border-color: red;
  border-left: double;
  color: black
}

In the above example, the color of the left border is black, while the other borders are red. This is due to ‘border-left’ setting the width, style, and color. Since the color value is not given by the ‘border-left’ property, it will be taken from the ‘color’ property. The fact that the ‘color’ property is set after the ‘border-left’ property is not relevant.

5. Border Images

Authors can specify an image to be used in place of the border styles. In this case, the border's design is taken from the sides and corners of an image specified with ‘border-image-source’, whose pieces may be sliced, scaled and stretched in various ways to fit the size of the border image area. The border-image properties do not affect layout: layout of the box, its content, and surrounding content is based on the ‘border-width’ and ‘border-style’ properties only.

This example creates a top and bottom border consisting of a whole number of orange diamonds and a left and right border of a single, stretched diamond. The corners are diamonds of a different color. The image to tile is as follows. Apart from the diamonds, it is transparent:

Tile for border

The image is 81 by 81 pixels and has to be divided into 9 equal parts. The style rules could thus be as follows:

DIV {
  border-image: url("border.png") 27 round stretch;
  border: double orange 1em }

The result, when applied to a DIV of 12 by 5em, will be similar to this:

element with a diamond border

This shows a more complicated example, demonstrating how the border image corresponds to the fallback border-style but can also extend beyond the border area. The border image is a wavy green border with an extended corner effect:

The ‘border-image-source’ image, with the four ‘border-image-slice’ cuts at 124px diving the image into nine parts.

The rest of the border properties then interact to lay out the tiles as follows:

Diagram of all border-image properties and how they interact, and showing the rendering with and without the border-image in effect.

Here, even though the border-width is 12px, the ‘border-image-width’ property computes to 124px. The border-image area is then outset 31px from the border-box and into the margin area. If the border-image fails to load (or border images are not supported by the UA), the fallback rendering uses a green double border.

5.1. The ‘border-image-source’ property

Name: | border-image-source
Value: | none | <image>
Initial: | none
Applies to: | All elements, except internal table elements when ‘border-collapse’ is ‘collapse’
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | ‘none’ or the image with its URI made absolute

Specifies an image to use instead of the border styles given by the ‘border-style’ properties and as an additional background layer for the element. If the value is ‘none’ or if the image cannot be displayed, the border styles will be used.

5.2. The ‘border-image-slice’ property

Name: | border-image-slice
Value: | [<number> | <percentage>]{1,4} && fill?
Initial: | 100%
Applies to: | All elements, except internal table elements when ‘border-collapse’ is ‘collapse’
Inherited: | no
Percentages: | refer to size of the border image
Media: | visual
Computed value: | as specified

The four ‘border-image-slice’ values represent inward offsets from the top, right, bottom, and left edges of the image respectively, dividing it into nine regions: four corners, four edges and a middle. The middle image part is discarded (treated as fully transparent) unless the ‘fill’ keyword is present. (It is drawn over the background; see the border-image drawing process.)

If the fourth number/percentage is absent, it is the same as the second. If the third one is also absent, it is the same as the first. If the second one is also absent, it is the same as the first.

<percentage>
Percentages are relative to the size of the image: the width of the image for the horizontal offsets, the height for vertical offsets.
<number>
Numbers represent pixels in the image (if the image is a raster image) or vector coordinates (if the image is a vector image).
‘fill’
The ‘fill’ keyword, if present, causes the middle part of the border-image to be preserved. (By default it is discarded, i.e., treated as empty.)

Negative values are not allowed and values bigger than the size of the image are interpreted as ‘100%’.

The regions given by the ‘border-image-slice’ values may overlap. However if the sum of the right and left widths is equal to or greater than the width of the image, the images for the top and bottom edge and the middle part are empty, which has the same effect as if a nonempty transparent image had been specified for those parts. Analogously for the top and bottom values.

Diagram: two horizontal cuts and two vertical cuts through an image

Diagram illustrating the cuts corresponding to the value ‘25% 30% 12% 20%’

5.3. The ‘border-image-width’ property

Name: | border-image-width
Value: | [ <length> | <percentage> | <number> | auto ]{1,4}
Initial: | 1
Applies to: | All elements, except table elements when ‘border-collapse’ is ‘collapse’
Inherited: | no
Percentages: | Relative to width/height of the border image area
Media: | visual
Computed value: | all <length>s made absolute, otherwise as specified

The border image is drawn inside an area called the border image area. This is an area whose boundaries by default correspond to the border box, see ‘border-image-outset’.

The four values of ‘border-image-width’ specify offsets that are used to divide the border image area into nine parts. They represent inward distances from the the top, right, bottom, and left sides of the area, respectively. If the fourth value is absent, it is the same as the second. If the third one is also absent, it is the same as the first. If the second one is also absent, it is the same as the first. Values have the following meanings:

<percentage>
Percentages refer to the size of the border image area: the width of the area for horizontal offsets, the height for vertical offsets.
<number>
Numbers represent multiples of the corresponding border-width.
‘auto’
If ‘auto’ is specified then the border image width is the intrinsic width or height (whichever is applicable) of the corresponding image slice (see ‘border-image-slice’). If the image does not have the required intrinsic dimension then the corresponding border-width is used instead.

Are percentages of the border-image area useful? Should percentages be used instead of numbers for ratios?

Negative values are not allowed for any ‘border-image-width’ values.

If two opposite ‘border-image-width’ offsets are large enough that they overlap, then the used values of all ‘border-image-width’ offsets are proportionally reduced until they no longer overlap. In mathematical notation: Given Lwidth as the width of the border image area, Lheight as its height, and Wside as the border image width offset for the side side, let f = min(Lwidth/(Wleft+Wright), Lheight/(Wtop+Wbottom)). If f < 1, then all W are reduced by multiplying them by f.

5.4. The ‘border-image-outset’ property

Name: | border-image-outset
Value: | [ <length> | <number> ]{1,4}
Initial: | 0
Applies to: | All elements, except internal table elements when ‘border-collapse’ is ‘collapse’
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | all <length>s made absolute, otherwise as specified

The values specify the amount by which the border image area extends beyond the border box on the top, right, bottom, and left sides respectively. If the fourth value is absent, it is the same as the second. If the third one is also absent, it is the same as the first. If the second one is also absent, it is the same as the first. Numbers represent multiples of the corresponding border-width.

Negative values are not allowed for any of the ‘border-image-outset’ values.

Portions of the border-image that are rendered outside the border box do not trigger scrolling. Also such portions are invisible to mouse events and do not capture such events on behalf of the element.

Note that, even though they never cause a scrolling mechanism, they may still be clipped by an ancestor or by the viewport.

5.5. The ‘border-image-repeat’ property

Name: | border-image-repeat
Value: | [ stretch | repeat | round ]{1,2}
Initial: | stretch
Applies to: | All elements, except internal table elements when ‘border-collapse’ is ‘collapse’
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified

This property specifies how the images for the sides and the middle part of the border image are scaled and tiled. If the second keyword is absent, it is assumed to be the same as the first. Values have the following meanings:

‘stretch’
The image is stretched to fill the area.
‘repeat’
The image is tiled (repeated) to fill the area.
‘round’
The image is tiled (repeated) to fill the area. If it does not fill the area with a whole number of tiles, the image is rescaled so that it does.
‘space’
The image is tiled (repeated) to fill the area. If it does not fill the area with a whole number of tiles, the extra space is distributed around the tiles.

The exact process for scaling and tiling the border-image parts is given in the section below.

5.6. Border-image drawing process

After the border-image given by ‘border-image-source’ is sliced by the ‘border-image-slice’ values, the resulting nine images are scaled, positioned, and tiled into their corresponding border image regions in four steps:

  1. Scale to ‘border-image-width’.

    • The two images for the top and bottom edges are made as tall as the top and bottom border image area parts, respectively, and their width is scaled proportionally.

    • The images for the left and right edge are made as wide as the left and right border image area parts, respectively, and their height is scaled proportionally.

    • The corner images are scaled to be as wide and as tall as the two border-image edges they are part of.

    • The middle image's width is scaled by the same factor as the top image unless that factor is zero or infinity, in which case the scaling factor of the bottom is substituted, and failing that, the width is not scaled. The height of the middle image is scaled by the same factor as the left image unless that factor is zero or infinity, in which case the scaling factor of the right image is substituted, and failing that, the height is not scaled.

  2. Scale to ‘border-image-repeat’.

    • If the first keyword is ‘stretch’, the top, middle and bottom images are further scaled to be as wide as the middle part of the border image area. The height is not changed any further.

    • If the first keyword is ‘round’, the top, middle and bottom images are resized in width, so that exactly a whole number of them fit in the middle part of the border-image area, exactly as for ‘round’ in the ‘background-repeat’ property.

    • If the first keyword is ‘repeat’ or ‘space’, the top, middle, and bottom images are not changed any further.

    • The effects of ‘stretch’, ‘round’, ‘repeat’, and ‘space’ for the second keyword are analogous, acting on the height of the left, middle and right images.

  3. Position the first tile.

    • If the first keyword is ‘repeat’, the top, middle, and bottom images are centered horizontally in their respective areas. Otherwise the images are placed at the left edge of their respective parts of the border-image area.

    • If the second keyword is ‘repeat’, the left, middle, and right images are centered vertically in their respective areas. Otherwise the images are placed at the top edge of their respective parts of the border-image area.

  4. Tile and draw.

    • The images are then tiled to fill their respective areas. All images are drawn at the same stacking level as normal borders: immediately in front of the background layers.

    • In the case of ‘space’, any partial tiles are discarded and the extra space distributed before, after, and between the tiles. (I.e. the gap before the first tile, the gap after the last tile, and the gaps between tiles are equalized.) This can result in empty border-image side areas.

5.7. The ‘border-image’ shorthand

Name: | border-image
Value: | <‘border-image-source’> || <‘border-image-slice’> [ / <‘border-image-width’>? [ / <‘border-image-outset’> ]? ]? || <‘border-image-repeat’>
Initial: | See individual properties
Applies to: | See individual properties
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | See individual properties

This is a shorthand property for setting ‘border-image-source’, ‘border-image-slice’, ‘border-image-width’, ‘border-image-outset’ and ‘border-image-repeat’. Omitted values are set to their initial values.

6. Miscellaneous Effects

6.1. The ‘box-decoration-break’ property

Name: | box-decoration-break
Value: | slice | clone
Initial: | slice
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified

When a box is broken at a page break, column break, or, for inline elements, at a line break, the ‘box-decoration-break’ property specifies whether individual boxes are treated as broken pieces of one continuous box, or whether each box is individually wrapped with the border and padding. For backgrounds it defines how the background positioning area is derived from these multiple boxes and how the element's background is drawn within them. Values have the following meanings:

‘clone’
Each box is independently wrapped with the border and padding. The ‘border-radius’ and ‘border-image’ and ‘box-shadow’, if any, are applied to each box independently. The background is drawn independently in each box of the element. A no-repeat background image will thus be rendered once in each box of the element.
‘slice’

No border and no padding are inserted at the break. No box-shadow is drawn at the broken edge; ‘border-radius’ has no effect at its corners; and the ‘border-image’ is rendered for the whole box as if it were unbroken. The effect is as though the element were rendered with no break present, and then sliced by the break afterward.

Backgrounds are drawn as if, after the element has been laid out (including any justification, bidi reordering, page breaks, etc.), all the element's boxes are taken and put one after the other in visual order. The background is applied to the bounding box of this composite box and then the boxes are put back, with their share of the background.

For boxes broken across lines, first boxes on the same line are connected in visual order. Then boxes on subsequent lines are ordered according to the element's inline progression direction and aligned on the baseline. For example in a left-to-right containing block (‘direction’ is ‘ltr’), the first box is the leftmost box on the first line and boxes from subsequent lines are put to the right of it. In a right-to-left containing block, the first box is the rightmost on the first line and subsequent boxes are put to the left of it.

For boxes broken across columns, the columns are treated as one continuous element, as if the column boxes were glued together in the block progression direction of the multi-column element. For boxes broken across pages, the page content areas are glued together in the block progression direction of the root element. In these cases, if the pieces have different widths (heights, if the root element / multi-column element is in vertical text mode), then each piece draws its background assuming that the whole element has the same width (height) as this piece. This ensures that right-aligned images stay aligned to the right edge, left-aligned images stay aligned to the left edge, and centered images stay centered.

Illustration: (1) a single box cut in two in between two lines of text by a page break and (2) two boxes, one before and one after the page break, both with a border all around and their own background image

Two possibilities for ‘box-decoration-break’: on the left, the value ‘slice’, on the right the value ‘clone’.

For inline elements side of the box that breaks is determined by the element's inline progression direction, not that of the containing block. For example, the first part of an inline element with ‘direction: rtl’ inside a block with ‘direction: ltr’ will break on the left side.

6.2. The ‘box-shadow’ property

Name: | box-shadow
Value: | none | <shadow> [ , <shadow> ]*
Initial: | none
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | any <length> made absolute; any color computed; otherwise as specified

The ‘box-shadow’ property attaches one or more drop-shadows to the box. The property is a comma-separated list of shadows, each specified by 2-4 length values, an optional color, and an optional ‘inset’ keyword. Omitted lengths are 0; omitted colors are a UA-chosen color.

Where

<shadow> = inset? && [ <length>{2,4} && <color>? ]

The components of each <shadow> are interpreted as follows:

  • The first length is the horizontal offset of the shadow. A positive value draws a shadow that is offset to the right of the box, a negative length to the left.
  • The second length is the vertical offset. A positive value offsets the shadow down, a negative one up.
  • The third length is a blur distance. Negative values are not allowed. If the blur value is zero, the shadow's edge is sharp. Otherwise, the larger the value, the more the shadow's edge is blurred. See below.
  • The fourth length is a spread distance. Positive values cause the shadow shape to expand in all directions by the specified radius. Negative values cause the shadow shape to contract. See below. Note that for inner shadows, expanding the shadow (creating more shadow area) means contracting the shadow's perimeter shape.
  • The color is the color of the shadow.
  • The ‘inset’ keyword, if present, changes the drop shadow from an outer shadow (one that shadows the box onto the canvas, as if it were lifted above the canvas) to an inner shadow (one that shadows the canvas onto the box, as if the box were cut out of the canvas and shifted behind it).

An outer box-shadow casts a shadow as if the border-box of the element were opaque. The shadow is drawn outside the border edge only: it is clipped inside the border-box of the element.

An inner box-shadow casts a shadow as if everything outside the padding edge were opaque. The inner shadow is drawn inside the padding edge only: it is clipped outside the padding box of the element.

If the box has a nonzero ‘border-radius’, the shadow shape is rounded in the same way. The ‘border-image’ does not affect the shape of the box-shadow.

If a spread distance is defined, the shadow is expanded outward or contracted inward by an operation equivalent to applying twice the absolute value of the spread value to a blur operation as defined below and thresholding the result such that for a positive spread distance all non-transparent pixels are given the full shadow color and for a negative spread distance all non-opaque pixels are made transparent. The UA may approximate this operation by taking an outward outset of the specified amount normal to the original shadow perimeter. Alternatively the UA may approximate the transformed shadow perimeter shape by outsetting (insetting, for inner shadows) the shadow's straight edges by the spread distance and increasing (decreasing, for inner shadows) and flooring at zero the corner radii by the same amount. (The UA may even combine these methods, using one method for outer shadows and another for inner ones.) For corners with a zero border-radius, however, the corner must remain sharp—the operation is equivalent to scaling the shadow shape. In any case, the effective width and height of the shadow shape is floored at zero. (A zero-sized shadow shape would cause an outer shadow to disappear, and an inner shadow to cover the entire padding-box.)

A non-zero blur distance indicates that the resulting shadow should be blurred, such as by a Gaussian filter. The exact algorithm is not defined; however for a long, straight shadow edge, this should create a color transition the length of the blur distance that is perpendicular to and centered on the shadow's edge, and that ranges from the full shadow color at the radius endpoint inside the shadow to fully transparent at the endpoint outside it.

The example below demonstrates the effects of spread and blur on the shadow:

An example of spread and blur on a box with two round corners and two square ones

The shadow effects are applied front-to-back: the first shadow is on top and the others are layered behind. Shadows do not influence layout and may overlap other boxes or their shadows. In terms of stacking contexts and the painting order, the outer shadows of an element are drawn immediately below the background of that element, and the inner shadows of an element are drawn immediately above the background of that element (below the borders and border image, if any).

If an element has multiple boxes, all of them get drop shadows, but shadows are only drawn where borders would also be drawn; see ‘box-decoration-break’.

Shadows do not trigger scrolling or increase the size of the scrollable area.

Below are some examples of an orange box with a blue border being being given a drop shadow.

border:5px solid blue;
background-color:orange;
width: 144px;
height: 144px;
border-radius: 20px;
border-radius: 0;
box-shadow:
  rgba(0,0,0,0.4)
  10px 10px;
 A round-cornered box with a light gray shadow the same shape as the border box offset 10px to the right and 10px down from directly underneath the box. A square-cornered box with a light gray shadow the same shape as the border box offset 10px to the right and 10px down from directly underneath the box.
box-shadow:
  rgba(0,0,0,0.4)
  10px 10px
  inset
 A round-cornered box with a light gray shadow the inverse shape of the padding box filling 10px in from the top and left edges (just inside the border). A square-cornered box with a light gray shadow the inverse shape of the padding box filling 10px in from the top and left edges (just inside the border).
box-shadow:
  rgba(0,0,0,0.4)
  10px 10px 0
  10px /* spread */
 A round-cornered box with a light gray shadow the same shape as the box but 20px taller and wider and offset so that the top and left edges of the shadow are directly underneath the top and left edges of the box. A square-cornered box with a light gray shadow the same shape as the box but 20px taller and wider and offset so that the top and left edges of the shadow are directly underneath the top and left edges of the box.
box-shadow:
  rgba(0,0,0,0.4)
  10px 10px 0
  10px /* spread */
  inset
 A round-cornered box with a light gray shadow the inverse shape of the box but 20px narrower and shorter filling 20px in from the top and left edges (just inside the border). A round-cornered box with a light gray shadow the inverse shape of the box but 20px narrower and shorter filling 20px in from the top and left edges (just inside the border).

The ‘box-shadow’ property applies to the ‘::first-letter’ pseudo-element, but not the ‘::first-line’ pseudo-element. Outer shadows have no effect on internal table elements in the collapsing border model. If a shadow is defined for single border edge in the collapsing border model that has multiple border thicknesses (e.g. an outer shadow on a table where one row has thicker borders than the others, or an inner shadow on a rowspanning table cell that adjoins cells with different border thicknesses), the exact position and rendering of its shadows are undefined.

7. Definitions

7.1. Glossary

The following terms and abbreviations are used in this module.

UA
User Agent

A program that reads and/or writes CSS style sheets on behalf of a user in either or both of these categories: programs whose purpose is to render documents (e.g., browsers) and programs whose purpose is to create style sheets (e.g., editors). A UA may fall into both categories. (There are other programs that read or write style sheets, but this module gives no rules for them.)

document

A tree-structured document with elements and attributes, such as an SGML or XML document [XML11].

style sheet

A CSS style sheet.

7.2. Conformance

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification. All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Conformance to CSS Backgrounds and Borders Level 3 is defined for three classes:

style sheet
A CSS style sheet.
renderer
A UA that interprets the semantics of a style sheet and renders documents that use them.
authoring tool
A UA that writes a style sheet.

A style sheet is conformant to CSS Backgrounds and Borders Level 3 if all of its declarations that use properties defined in this module have values that are valid according to the generic CSS grammar and the individual grammars of each property as given in this module.

A renderer is conformant to CSS Backgrounds and Borders Level 3 if, in addition to interpreting the style sheet as defined by the appropriate specifications, it supports all the properties defined by CSS Backgrounds and Borders Level 3 by parsing them correctly and rendering the document accordingly. However the inability of a UA to correctly render a document due to limitations of the device does not make the UA non-conformant. (For example, a UA is not required to render color on a monochrome monitor.)

An authoring tool is conformant to CSS Backgrounds and Borders Level 3 if it writes syntactically correct style sheets, according to the generic CSS grammar and the individual grammars of each property in this module.

7.3. Levels

This section is informative. CSS has different levels of features, each a subset of the other. (See [CSSBEIJING] for a full explanation.) The lists below describe which features from this specification are in each level.

7.3.1. CSS Level 1

  • ‘background-color’
  • ‘background-image’ only one image (no layers)
  • ‘background-repeat’: only ‘repeat’ | ‘repeat-x’ | ‘repeat-y’ | ‘no-repeat’
  • ‘background-attachment’: only ‘scroll’ | ‘fixed’
  • ‘background-position’: only one or two values allowed
  • ‘background’ shorthand: only color, image, repeat, attachment and position
  • ‘border-color’ properties
  • ‘border-style’ properties
  • ‘border-width’ properties
  • ‘border-top’, ‘border-bottom’, ‘border-right’, ‘border-left’, and ‘border’ shorthands

7.3.2. CSS Level 2

  • ‘background-color’
  • ‘background-image’: only one image (no layers)
  • ‘background-repeat’: only ‘repeat’ | ‘repeat-x’ | ‘repeat-y’ | ‘no-repeat’
  • ‘background-attachment’: only ‘scroll’ | ‘fixed’
  • ‘background-position’: only one or two values allowed
  • ‘background’: only color, image, repeat, attachment and position
  • ‘border-color’ properties
  • ‘border-style’ properties
  • ‘border-width’ properties
  • ‘border-top’, ‘border-bottom’, ‘border-right’, ‘border-left’, and ‘border’ shorthands

7.3.3. CSS Level 3

  • All features described in the CSS Backgrounds and Borders Module Level 3

7.4. CR exit criteria

As described in the W3C process document, a Candidate Recommendation (CR) is a specification that W3C recommends for use on the Web. The next stage is “Recommendation,” when the specification is sufficiently implemented.

For this specification to be proposed as a W3C Recommendation, the following conditions shall be met. There must be at least two independent, interoperable implementations of each feature. Each feature may be implemented by a different set of products, there is no requirement that all features be implemented by a single product. For the purposes of this criterion, we define the following terms:

independent
each implementation must be developed by a different party and cannot share, reuse, or derive from code used by another qualifying implementation. Sections of code that have no bearing on the implementation of this specification are exempt from this requirement.
interoperable
passing the respective test case(s) in the official CSS test suite, or, if the implementation is not a Web browser, an equivalent test. Every relevant test in the test suite should have an equivalent test created if such a user agent (UA) is to be used to claim interoperability. In addition if such a UA is to be used to claim interoperability, then there must one or more additional UAs which can also pass those equivalent tests in the same way for the purpose of interoperability. The equivalent tests must be made publicly available for the purposes of peer review.
implementation
a user agent which:
  1. implements the specification.
  2. is available to the general public. The implementation may be a shipping product or other publicly available version (i.e., beta version, preview release, or “nightly build”). Non-shipping product releases must have implemented the feature(s) for a period of at least one month in order to demonstrate stability.
  3. is not experimental (i.e., a version specifically designed to pass the test suite and is not intended for normal usage going forward).

A minimum of sixth months of the CR period must have elapsed. This is to ensure that enough time is given for any remaining major errors to be caught.

Features will be dropped if two or more interoperable implementations are not found by the end of the CR period.

Features may/will also be dropped if adequate/sufficient (by judgment of CSS WG) tests have not been produced for those feature(s) by the end of the CR period.

8. Changes Since the 17 December 2009 Candidate Recommendation

The following changes were made to this specification since the 17 December 2009 Candidate Recommendation:

  • Addition of ‘content-box’ value of ‘background-clip’.
  • Change to the ‘background’ shorthand syntax for ‘background-clip’ and ‘background-origin’.
  • Removal of recommendation to use gradients for color transitions when ‘border-radius’ produces a curve.
  • (Re)Addition of ‘box-shadow’ property.
  • Various clarifications.

9. Acknowledgments

Tapas Roy was editor of the Border Module, before it was merged with the Background Module.

Thanks to Ben Stucki for defining what happens with rounded corners if the two adjoining borders are of unequal thickness or one of them is zero; to Arjan Eising and Anne van Kesteren for the ‘border-radius’ syntax; to Zack Weinberg for the corner transition regions diagram.

A set of properties for border images was initially proposed by fantasai. The current simplification (one image cut into nine parts) is due to Ian Hickson. (Though the original idea seems to originate with some anonymous Microsoft engineers.)

Finally, special thanks go to Brad Kemper for his feedback and suggestions for many of the features in the draft, for drawing all the box-shadow examples, and for proposing some radical changes to the ‘border-image’ property that solved a number of problems with the earlier definition.

10. References

Normative references

[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 8 September 2009. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2009/CR-CSS2-20090908
[CSS3COLOR]
Tantek Çelik; Chris Lilley; L. David Baron. CSS Color Module Level 3. 21 July 2008. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2008/WD-css3-color-20080721
[HTML401]
David Raggett; Ian Jacobs; Arnaud Le Hors. HTML 4.01 Specification. 24 December 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-html401-19991224
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[XHTML11]
Murray Altheim; Shane McCarron. XHTML™ 1.1 - Module-based XHTML. 31 May 2001. W3C Recommendation. URL: http://www.w3.org/TR/2001/REC-xhtml11-20010531

Other references

[CSS1]
Håkon Wium Lie; Bert Bos. Cascading Style Sheets (CSS1) Level 1 Specification. 11 April 2008. W3C Recommendation. URL: http://www.w3.org/TR/2008/REC-CSS1-20080411
[CSSBEIJING]
Elika J. Etemad. Cascading Style Sheets (CSS) Snapshot 2007. 16 May 2008. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2008/WD-css-beijing-20080516
[XML11]
Eve Maler; et al. Extensible Markup Language (XML) 1.1 (Second Edition). 16 August 2006. W3C Recommendation. URL: http://www.w3.org/TR/2006/REC-xml11-20060816

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
background | [ <bg-layer> , ]* <final-bg-layer> | see individual properties | all elements | no | see individual properties | visual
background-attachment | <attachment> [ , <attachment> ]* | scroll | all elements | no | N/A | visual
background-clip | <box> [ , <box> ]* | border-box | all elements | no | N/A | visual
background-color | <color> | transparent | all elements | no | N/A | visual
background-image | <bg-image> [ , <bg-image> ]* | none | all elements | no | N/A | visual
background-origin | <box> [ , <box> ]* | padding-box | all elements | no | N/A | visual
background-position | <bg-position> [ , <bg-position> ]* | 0% 0% | all elements | no | refer to size of background positioning area minus size of background image; see text | visual
background-repeat | <repeat-style> [ , <repeat-style> ]* | repeat | all elements | no | N/A | visual
background-size | <bg-size> [ , <bg-size> ]* | auto | all elements | no | see text | visual
border | <border-width> || <border-style> || <color> | See individual properties | all elements | no | N/A | visual
border-color | <color>{1,4} | (see individual properties) | all elements | no | N/A | visual
border-image | <‘border-image-source’> || <‘border-image-slice’> [ / <‘border-image-width’>? [ / <‘border-image-outset’> ]? ]? || <‘border-image-repeat’> | See individual properties | See individual properties | no | N/A | visual
border-image-outset | [ <length> | <number> ]{1,4} | 0 | All elements, except internal table elements when ‘border-collapse’ is ‘collapse’ | no | N/A | visual
border-image-repeat | [ stretch | repeat | round ]{1,2} | stretch | All elements, except internal table elements when ‘border-collapse’ is ‘collapse’ | no | N/A | visual
border-image-slice | [<number> | <percentage>]{1,4} && fill? | 100% | All elements, except internal table elements when ‘border-collapse’ is ‘collapse’ | no | refer to size of the border image | visual
border-image-source | none | <image> | none | All elements, except internal table elements when ‘border-collapse’ is ‘collapse’ | no | N/A | visual
border-image-width | [ <length> | <percentage> | <number> | auto ]{1,4} | 1 | All elements, except table elements when ‘border-collapse’ is ‘collapse’ | no | Relative to width/height of the border image area | visual
border-radius | [ <length> | <percentage> ]{1,4} [ / [ <length> | <percentage> ]{1,4} ]? | 0 | all elements, except table element when ‘border-collapse’ is ‘collapse’ | no | Refer to corresponding dimension of the border box. | visual
border-style | <border-style>{1,4} | (see individual properties) | all elements | no | N/A | visual
border-top, border-right, border-bottom, border-left | <border-width> || <border-style> || <color> | See individual properties | all elements | no | N/A | visual
border-top-color , border-right-color, border-bottom-color, border-left-color | <color> | currentcolor | all elements | no | N/A | visual
border-top-right-radius, border-bottom-right-radius, border-bottom-left-radius, border-top-left-radius | [ <length> | <percentage> ] [ <length> | <percentage> ]? | 0 | all elements (but see prose) | no | Refer to corresponding dimension of the border box. | visual
border-top-style, border-right-style, border-bottom-style, border-left-style | <border-style> | none | all elements | no | N/A | visual
border-top-width, border-right-width, border-bottom-width, border-left-width | <border-width> | medium | all elements | no | width* of containing block | visual
border-width | <border-width>{1,4} | (see individual properties) | all elements | no | see individual properties | visual
box-decoration-break | slice | clone | slice | all elements | no | N/A | visual
box-shadow | none | <shadow> [ , <shadow> ]* | none | all elements | no | N/A | visual

Index

  • <attachment>, 3.5.
  • authoring tool, 7.2.
  • ‘auto’
    • ‘background-size’ value, 3.9.
    • ‘border-image-width’ value, 5.3.
  • background, 3.10.
  • background-attachment, 3.5.
  • background-clip, 3.7.
  • background-color, 3.2.
  • background-image, 3.3.
  • background-origin, 3.8.
  • background painting area, 3.7.
  • background painting area., 3.4.
  • background-position, 3.6.
  • background positioning area., 3.9.
  • background positioning area, 3.8., 3.4., 6.1.
  • background positioning area, 3.6.
  • background-repeat, 3.4.
  • background-size, 3.9.
  • <bg-image>, 3.3.
  • <bg-layer>, 3.10.
  • <bg-position>, 3.6.
  • <bg-size>, 3.9.
  • border, 4.5.
  • border-bottom, 4.5.
  • border-bottom-color, 4.1.
  • border-bottom-left-radius, 4.4.
  • border-bottom-right-radius, 4.4.
  • border-bottom-style, 4.2.
  • border-bottom-width, 4.3.
  • ‘border-box’
    • ‘background-clip’ value, 3.7.
    • ‘background-origin’ value, 3.8.
  • border-color, 4.1.
  • border-image, 5.7.
  • border image area, 5.4.
  • border-image-outset, 5.4.
  • border-image-repeat, 5.5.
  • border-image-slice, 5.2.
  • border-image-source, 5.1.
  • border-image-width, 5.3.
  • border-left, 4.5.
  • border-left-color, 4.1.
  • border-left-style, 4.2.
  • border-left-width, 4.3.
  • border-radius, 4.4.
  • border-right, 4.5.
  • border-right-color, 4.1.
  • border-right-style, 4.2.
  • border-right-width, 4.3.
  • <border-style>, 4.2.
  • border-style, 4.2.
  • border-top, 4.5.
  • border-top-color, 4.1.
  • border-top-left-radius, 4.4.
  • border-top-right-radius, 4.4.
  • border-top-style, 4.2.
  • border-top-width, 4.3.
  • <border-width>, 4.3.
  • border-width, 4.3.
  • ‘bottom’
    • ‘background-position’ value, 3.6.
  • <box>, 3.7.
  • box-decoration-break, 6.1.
  • box-shadow, 6.2.
  • ‘center’
    • ‘background-position’ value, 3.6.
  • ‘clone’, 6.1.
  • color
    • background, 3.2.
  • <color>, 2.
  • ‘contain’, 3.9.
  • ‘content-box’, 3.8.
    • ‘background-clip’ value, 3.7.
  • ‘cover’, 3.9.
  • ‘dashed’, 4.2.
  • document, 7.1.
  • documents, 7.1.
  • ‘dotted’, 4.2.
  • ‘double’, 4.2.
  • ‘fill’, 5.2.
  • <final-bg-layer>, 3.10.
  • fixed, 3.5.
  • ‘fixed’, 3.5.
  • ‘groove’, 4.2.
  • ‘hidden’, 4.2.
  • <image>, 2.
  • ‘inset’, 4.2.
  • layers, 3.1.
  • ‘left’
    • ‘background-position’ value, 3.6.
  • local, 3.5.
  • ‘local’, 3.5.
  • ‘none’
    • ‘background-image’ value, 3.3.
    • ‘border-image-source’ value, 5.1.
    • ‘border-style’ value, 4.2.
  • ‘no-repeat’
    • ‘background-repeat’ value, 3.4.
  • ‘outset’, 4.2.
  • ‘padding-box’
    • ‘background-clip’ value, 3.7.
    • ‘background-origin’ value, 3.8.
  • renderer, 7.2.
  • ‘repeat’
    • ‘background-repeat’ value, 3.4.
    • ‘border-image-repeat’ value, 5.5.
  • <repeat-style>, 3.4.
  • ‘repeat-x’, 3.4.
  • ‘repeat-y’, 3.4.
  • ‘ridge’, 4.2.
  • ‘right’
    • ‘background-position’ value, 3.6.
  • ‘round’
    • ‘background-repeat’ value, 3.4.
    • ‘border-image-repeat’ value, 5.5.
  • scroll, 3.5.
  • ‘scroll’, 3.5.
  • <shadow>, 6.2.
  • ‘slice’, 6.1.
  • ‘solid’, 4.2.
  • ‘space’
    • ‘background-repeat’ value, 3.4.
    • ‘border-image-repeat’ value, 5.5.
  • ‘stretch’, 5.5.
  • style sheet, 7.1.
    • as conformance class, 7.2.
  • ‘top’
    • ‘background-position’ value, 3.6.
  • UA, 7.1.
  • User Agent, 7.1.
  • viewport, 3.5.


CSS3 basic box model

CSS basic box model

W3C Working Draft 9 August 2007

This version:
http://www.w3.org/TR/2007/WD-css3-box-20070809
Latest version:
http://www.w3.org/TR/css3-box
Previous version:
http://www.w3.org/TR/2002/WD-css3-box-20021024
Editors:
Bert Bos (W3C) bert@w3.org

Copyright © 2007 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

CSS (Cascading Style Sheets) describes the rendering of documents on various media. When textual documents (e.g., HTML) are laid out on visual media (e.g., screen or print), CSS models the document as a hierarchy of boxes containing words, lines, paragraphs, tables, etc. each with properties such as size, color and font.

This module describes the basic types of boxes, with their padding and margin, and the normal “flow” (i.e., the sequence of blocks of text with margins in-between). It also defines “floating” boxes, but other kinds of layout, such as tables, absolute positioning, ruby annotations, grid layouts, columns and numbered pages, are described by other modules. Also, the layout of text inside each line (including the handling of left-to-right and right-to-left scripts) is defined elsewhere.

Boxes may contain either horizontal or vertical lines of text. Boxes of different orientations may be mixed in one flow. (This is a level 3 feature.)

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css3-box” in the subject, preferably like this: “[css3-box] …summary of comment…”

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This module should eventually replace corresponding parts of the revised CSS level 2 specification [CSS21]. But this is an early draft and any differences to level 2 are most likely unintentional, unless they concern new features, such as vertical text or the marquee effect. Please help us improve the next draft by pointing out such differences.

Table of contents

  • 1. Dependencies on other modules
  • 2. Introduction
  • 3. How to read this specification
  • 4. Types of boxes
    • 4.1. The ‘display’ property
    • 4.2. Block-level boxes, containing blocks, flows and anonymous boxes
    • 4.3. Run-in boxes
    • 4.4. Compact boxes
  • 5. The padding properties
  • 6. Margins
    • 6.1. The margin properties
    • 6.2. Collapsing margins
  • 7. The ‘width’ and ‘height’ properties
  • 8. The ‘min-width’, ‘max-width’, ‘min-height’ and ‘max-height’ properties
  • 9. Calculating widths, heights and margins
    • 9.1. Inline, non-replaced elements
    • 9.2. Inline or floating, replaced elements
    • 9.3. Block-level, non-replaced elements in normal flow when ‘overflow’ computes to ‘visible’
    • 9.4. Other block-level, non-replaced elements in normal flow
    • 9.5. ‘Inline-block’ or floating, non-replaced elements
    • 9.6. Absolutely positioned, non-replaced elements
    • 9.7. Absolutely positioned, replaced elements
    • 9.8. Block-level, replaced elements in normal flow
    • 9.9. Floating, non-replaced elements
    • 9.10. ‘Auto’ heights for flow roots
    • 9.11. Shrink-to-fit
  • 10. Floating boxes
    • 10.1. Introduction to floats
    • 10.2. The ‘float’ property
    • 10.3. Rules for positioning floats
    • 10.4. The ‘clear’ property
  • 11. Overflow
    • 11.1. The ‘overflow’, ‘overflow-x’ and ‘overflow-y’ properties
    • 11.2. The ‘overflow-style’ property
    • 11.3. The marquee properties
  • 12. The ‘visibility’ property
  • 13. Rotating boxes
  • 14. Stacking contexts
  • 15. Conformance and profiles
  • 16. Acknowledgments
  • References
  • Index
  • Property index

1. Dependencies on other modules

This CSS module depends on the following other CSS modules:

  • CSS Text Layout Module [CSS3TEXTLAYOUT] – switch between vertical and horizontal text.
  • CSS Syntax Module [CSS3SYN] – syntax of properties and values
  • CSS Values and Units Module [CSS3VAL] – definitions of value types <number>, <angle> and <length>; defines the terms computed value and used value.
  • CSS Text Module [CSS3TEXT] – inline layout and definition of line box.
  • CSS Generated and Replaced Content module [CSS3GENCON] – defines the terms replaced element and intrinsic size (and intrinsic ratio).
  • CSS Backgrounds and Borders Module [CSS3BG] – defines <bg-position>

2. Introduction

Note: The model in this specification differs from the model described in the CSS level 2 specification [CSS21], because (1) it is generalized to apply also to vertical text and (2) it adds properties to control the marquee effect, (speed, direction, etc.). The marquee effect is allowed, but UA-dependent in level 2.

CSS assumes that the document to lay out is modeled as a tree of elements. Each element has an ordered list of zero or more child elements, with an optional string of text before the list, in-between the children and after the list. The unique element that has no parent is called the root element.

CSS describes how each element and each string of text is laid out by transforming the document tree into a tree of rectangular boxes, whose size and position depends on their properties. There are block-level boxes, line boxes and inline-level boxes. A block-level box is like a paragraph. A line box is like a line of text. And inline-level boxes are like words inside a line.

The precise rules are below and in other modules, but in summary, a block-level box contains either other block-level boxes (e.g., a section containing paragraphs, or a table containing rows), or it contains line boxes (e.g., a paragraph containing lines of text). A line box contains inline-level boxes (e.g., a line with words in different styles). An inline-level box may contain either text interspersed with more inline-level boxes, or it may contain a block-level box (e.g., a small table that is rendered inline).

Schematic representation of rel

Relation between four displayed boxes in the rendered document (on the right) and the three corresponding elements in the source document on the (left).

The tree of boxes closely mirrors the tree of elements. Each element is transformed into zero or more boxes. If the element is not the root element, then each of its boxes is either a child of a box of the parent element, or it is a child of a box of the element itself. In other words, there may be more or fewer boxes than there are elements, but each box belongs to exactly one element.

For example, a fragment of HTML such as

<ul>
 <li>The first item in the list.
 <li>The second item.
</ul>

may result in one block-level box for the ul element, containing two block-level boxes for the two li elements, each of which has one line box (i.e., one line of text). Both line boxes contain two inline-level boxes: one that contains the list bullet and one that contains the text.

Note how the li is transformed into multiple boxes, including one that contains “generated content,” viz., the list bullet, which is not present in the source document.

If the document is rendered in a narrow window, it may be that the li elements get transformed into even more boxes, because the text requires multiple lines. And if the document is rendered on paper, it may be that a page break falls in the middle of the ul element, so that it is not transformed into a single block-level box, but into two smaller ones, each on a different page.

Properties are set on elements and influence how the element is turned into boxes, but in this specification we refer interchangeably to “the P property of an element” and “the P property of a box” (both of which actually mean “the value of property P of…”), unless it is important to distinguish the box and the element, e.g., because the element has several boxes and they don't all have the same value for the property.

Diagram of a typical box, showing the content, padding, border and margin areas

The various areas and edges of a typical box

Boxes have padding, a border and margins (see the figure). Different properties determine the thickness of each of these (which may be zero).

Each box has a content area. The rectangle that bounds this area is the content edge. Around the content area is the padding area and its outside bounds are called the padding edge. Outside the padding is the border area and the outside boundary of that area is the border edge. Finally, outside the border is the margin area and its outer edge is the margin edge.

When the specification says that the padding or border is “absent” on some side of the box, that actually means that its thickness is zero.

Note that the margin, unlike the border and padding, may have a negative thickness. That is one way to make adjacent boxes overlap each other.

A box is horizontal if its ‘block-progression’ property is ‘tb’, otherwise it is vertical.

3. How to read this specification

All sections are normative, unless stated otherwise.

Examples look like this and normally start with the word “Example.” Examples are not normative.

Notes look like this and normally start with the word “Note.” Notes are not normative.

Editorial notes look like this. They will be removed before the document becomes Candidate Recommendation.

Each property is defined in part in the text and in part by a table that groups together a number of facts about the property, including a regular expression to restrict its syntax. See [where?] for the meaning. The “Inherited” and “Initial” rows in the table are used by the Cascading and Inheritance module [CSS3CASCADE] and “Media” by the Media Queries specification [MEDIAQ].

The specification may refer to the used value and the computed value of a property. Unless stated explicitly, the short form “value” means the computed value.

4. Types of boxes

4.1. The ‘display’ property

Name: | display
Value: | inline | block | inline-block | list-item | run-in | compact | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | ruby | ruby-base | ruby-text | ruby-base-group | ruby-text-group | <template>| none
Initial: | inline
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual (‘none’ applies to all media)
Computed value: | specified value, except for floats, root elements and positioned elements; see text

This property, in combination with ‘float’ and ‘position’, determines the type of box or boxes that are generated for an element. The values are as follows:

inline
Inline boxes.
block
Block boxes.
inline-block
A block box, which itself is flowed as a single inline box, similar to a replaced element. The inside of an inline-block is formatted as a block box, and the box itself is formatted as an inline box.
list-item
One or more block boxes and one marker box. Marker boxes are defined in the Lists module [CSS3LIST]. If the Lists module is not ready, define the position of the marker and the list-style property here? Or refer to CSS 2.1 instead?
run-in
Either block or inline boxes, depending on context (see Run-in boxes). Properties apply to run-in boxes based on their final status (inline-level or block-level).
compact
Either block boxes or a marker box, depending on context (see Compact boxes). Properties apply to compact boxes based on their final status.
table, inline-table, table-row-group, table-header-group, table-footer-group, table-row, table-column-group, table-column, table-cell, table-caption
See the Tables module [CSS3TBL].
ruby, ruby-base, ruby-text, ruby-base-group, ruby-text-group
See the Ruby module [CSS3RUBY].
<template>
See the Advanced Layout module [CSS3LAYOUT].
none
This value causes an element to generate no boxes (i.e., the element has no effect on layout). Descendant elements do not generate any boxes either; this behavior cannot be overridden by setting the ‘display’ property on the descendants.

Note that ‘none’ does not create an invisible box; it creates no box at all. See ‘visibility’ for a mechanisms that enables an element to generate boxes that affect formatting but are not visible themselves.

The computed value is the same as the specified value, except when ‘float’ is not ‘none’ or when the element is the root element. In those cases, the computed value is as follows:

Specified value | Computed value
inline-table | table
inline, run-in, table-row-group, table-column, table-column-group, table-header-group, table-footer-group, table-row, table-cell, table-caption, inline-block | block
others | same as specified

The value of ‘position’ may also influence the computed value. See [CSS3TBL].

In fact, the complete rules are:
  1. If ‘display’ is ‘none’, then ‘float’ and ‘position’ do not apply.
  2. Otherwise, if ‘position’ is neither ‘static’ nor ‘relative’, then ‘display’ is set according to the table above. (And float does not apply.)
  3. Otherwise, if float is not ‘none’, then ‘display’ is set according to the table above.
  4. Otherwise, if the element is the root element, then ‘display’ is set according to the table above.
  5. Otherwise, the computed value of ‘display’ is the same as the specified value.

4.2. Block-level boxes, containing blocks, flows and anonymous boxes

A block-level box is a box that has a used value for ‘display’ of ‘block’, ‘list-item’, ‘table’, ‘table-*’ (i.e., all table boxes) or <template>. A block-level element is an element all of whose top-level non-anonymous boxes are block-level.

An inline-level box is a box that has a used value for ‘display’ of ‘inline’, ‘inline-block’, ‘inline-table’ or ‘ruby’. [What about the other ruby values?]

An anonymous box, informally, is a box that cannot be addressed with CSS selectors. All its properties, except for ‘display’, have their default values (either the initial value or inherited). Anonymous boxes are created when the CSS box model requires a child box with a certain value for ‘display’, but the child actually has a different value. In that case an anonymous box of the right kind is created and wraps the child (or children). Other modules (e.g., [CSS3TBL], [CSS3TEXT]) may also define anonymous boxes. The anonymous boxes defined by this module are the following:

  • A block-level box may contain either line boxes or block-level boxes, but not both. If necessary, any line boxes that belong to this box's element are wrapped in one or more (as few as possible) anonymous boxes with a ‘display’ of ‘block’.

An example of the last point above is this document fragment:

<p>Somebody whose name I have
forgotten, said, long ago: <q>a box is
a box,</q> and he probably meant it.</p>

with these style rules:

p { display: block }
q { display: block; margin: 1em }

The p element has both line boxes and a child box for the q element, which is a block-level element. The line boxes before the q are wrapped in an anonymous block-level box and so are the line boxes after the q. The resulting tree of boxes might be as follows (refer to the figure):

  • block-level box [p]
    • block-level box [anonymous]
      • line box: “Somebody…”
      • line box: “forgotten…”
    • block-level box [q]
      • line box: “a box…”
    • block-level box [anonymous]
      • line box: “and he…”

The P element has two line boxes before the q and one after. The first two are wrapped in an anonymous box, the last one is wrapped in another anonymous box.

When the fragment is rendered, the text before the q is wrapped in an anonymous block and the text after the q in another.

Note that the anonymous boxes defined in this module are all block-level, but anonymous boxes defined in other modules may be different.

The containing block of a box is a rectangle that is associated with the box and that is used in various definitions in this specification. Apart from a size and a position, the rectangle also has ‘direction’ and ‘block-progression’ properties. The containing block of a box is defined as follows:

  • The containing block of the root element's top-level boxes is a rectangle with the dimensions of the viewport, anchored at the canvas's origin for continuous media and the page area for paged media. (See [MEDIAQ] and [CSS3PAGE] for definitions of continuous and paged media.) This containing block is called the initial containing block. The ‘direction’ and ‘block-progression’ of the initial containing block are the same as those of the root element.
  • The containing block of other boxes is the rectangle formed by the content edge of their nearest ancestor box that is block-level. This may be an anonymous box. The ‘direction’ and ‘block-progression’ of the containing block are those of the box whose content edge it is.

Note that the above is modified by the Absolute Positioning module [CSS3POS]: in particular, if a box's ‘position’ property is neither ‘static’ nor ‘relative’, its containing block is established differently.

A flow root is a box that satisfies at least one of the following:

  • The value of ‘float’ is not ‘none’.
  • The used value of ‘overflow’ is not ‘visible’.
  • The value of ‘display’ is ‘table-cell’, ‘table-caption’ (see [CSS3TBL]), ‘inline-block’ or ‘inline-table’.
  • The value of ‘position’ is neither ‘static’ nor ‘relative’ (see [CSS3POS]).
  • The value of ‘block-progression’ is ‘lr’ or ‘rl’ and the value of ‘block-progression’ of its parent box is ‘tb’
  • The value of ‘block-progression’ is ‘tb’ and the value of ‘block-progression’ of its parent box is ‘lr’ or ‘rl’.

Note that an element with ‘display: inline’ therefore cannot be a flow root: it doesn't float (otherwise its ‘display’ would be ‘block’), and neither ‘overflow’ nor ‘block-progression’ apply to inlines.

The terminology in the CSS level 2 specification is different. A flow root is called “an element that establishes a new formatting context.”

Other modules may define additional flow roots. [Can we thus remove ‘table-caption’, ‘table-cell’, and ‘position’ from the list above?]

The flow (a.k.a. normal flow) of a given flow root is a set of boxes. A box belongs to the flow if:

  1. The used value of its ‘display’ is ‘block’, ‘list-item’, ‘table’ or <template>.
  2. The used value of its ‘float’ is ‘none’.
  3. The used value of its ‘position’ is ‘static’ or ‘relative’.
  4. It is either a child of the flow root or a child of a box that belong to the flow.

For example, the fragment

<div class=sidebar>
 <p>Text in a sidebar.
 <p>Here is quote:
 <blockquote lang=ja>
  <p>...
 </blockquote>
 <p>Etc. etc.
</div>

with the style

div.sidebar { block-progression: tb; float: left }
blockquote[lang|=ja] { block-progression: rl; height: 10em }

defines two flows:

  1. The div is a flow root, because it floats. Its flow consist of the 1st, 2nd and 4th p and the blockquote.
  2. The blockquote is vertical, while its parent is horizontal and it is thus a flow root. Its flow is formed by the 3rd p.

(The div itself belongs to a third flow, but its flow root is not shown in the fragment.)

Note that a flow root is not necessarily block-level, it may be an ‘inline-block’, e.g.

The boxes of a flow are laid out inside their flow root one after the other in the direction of the ‘block-progression’ property of the flow root and in the same order as in the source document. Their position is given by how much their margins overlap (see “Collapsing margins”) and by the fact that their side margin edges coincide with content edges of their containing blocks. More precisely: Each box's left and right margin edges coincide with the left and right content edges of its containing block (if the flow root is ‘tb’), or its top and bottom margin edges coincide with the top and bottom content edges of its containing block (if the flow root is ‘rl’ or ‘lr’).

[Define viewport and canvas]

4.3. Run-in boxes

A run-in box behaves as follows:

  1. If the run-in box contains a block box, the run-in box becomes a block box.
  2. If a sibling block box (that does not float and is not absolutely positioned) follows the run-in box, the run-in box becomes the first inline box of the block box. A run-in cannot run in to a block that already starts with a run-in or that itself is a run-in.
  3. Otherwise, the run-in box becomes a block box.

A ‘run-in’ box is useful for run-in headers, as in this example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
  <HEAD>
    <TITLE>A run-in box example</TITLE>
    <STYLE type="text/css">
      H3 { display: run-in }
    </STYLE>
  </HEAD>
  <BODY>
    <H3>A run-in heading.</H3>
    <P>And a paragraph of text that
       follows it.
  </BODY>
</HTML>

This example might be formatted as:

A run-in heading. And a
paragraph of text that
follows it.

Despite appearing visually as part of the following block box, a run-in element still inherits properties from its parent in the source tree. Please consult the section on generated content for information about how run-in boxes interact with generated content. [where?]

4.4. Compact boxes

Define here or in extended box module?

5. The padding properties

Name: | padding
Value: | [ <length> | <percentage> ]{1,4}
Initial: | (see individual properties)
Applies to: | all elements
Inherited: | no
Percentages: | width* of containing block
Media: | visual
Computed value: | see individual properties
*) if the containing block is horizontal, otherwise the height
Name: | padding-top , padding-right, padding-bottom, padding-left
Value: | [ <length> | <percentage> ]
Initial: | 0
Applies to: | all elements
Inherited: | no
Percentages: | width* of containing block
Media: | visual
Computed value: | <length>
*) if the containing block is horizontal, otherwise the height

Sets the thickness of the padding area. The value may not be negative.

‘Padding’ is a shorthand for the other four properties. If ‘padding’ has four values, they are for top, right, bottom and left in that order. If left is omitted, it is the same as right. If bottom is omitted it is the same as top, if right is omitted it is the same as top.

Note that percentages on ‘padding-top’ and ‘padding-bottom’ are relative to the width of the containing block, not the height (at least in a horizontal flow; in a vertical flow they are relative to the height).

Note that percentages are not required for CSS level 2.

For example, the following two ways to set the padding of h1 are equivalent:

h1 { padding: 0.5em }
h1 { padding-top: 0.5em;
     padding-right: 0.5em;
     padding-bottom: 0.5em;
     padding-left: 0.5em }

6. Margins

6.1. The margin properties

Name: | margin-top , margin-right, margin-bottom, margin-left
Value: | <length> | <percentage> | auto
Initial: | 0
Applies to: | see text
Inherited: | no
Percentages: | width* of containing block
Media: | visual
Computed value: | the percentage as specified or the absolute length or ‘auto’
*) if the containing block is horizontal, otherwise the height
Name: | margin
Value: | [ <length> | <percentage> | auto ]{1,4}
Initial: | (see individual properties)
Applies to: | see text
Inherited: | no
Percentages: | width* of containing block
Media: | visual
Computed value: | see individual properties
*) if the containing block is horizontal, otherwise the height

These properties set the thickness of the margin area. The value may be negative.

‘Margin’ is a shorthand for the other four. If ‘margin’ has four values, they set top, right, bottom and left in that order. If left is omitted, it is the same as right. If bottom is omitted, it is the same as top. If right is omitted it is the same as top.

The properties apply to all boxes except certain table-* boxes (see [CSS3TBL]) and certain inline-level boxes (see [CSS3TEXT]).

Margins must satisfy certain constraints, which means that the used value may be different from the computed value. See “Calculating widths, heights and margins.”

Note that in a horizontal flow, percentages on ‘margin-top’ and ‘margin-bottom’ are relative to the width of the containing block, not the height (and in vertical flow, ‘margin-left’ and ‘margin-right’ are relative to the height, not the width).

For example, the following two ways of setting the margins of p are equivalent:

p { margin: 1em 2em }
p { margin-top: 1em;
    margin-right: 2em;
    margin-bottom: 1em;
    margin-left: 2em }

6.2. Collapsing margins

Certain adjoining margins combine to form a single margin. Those margins are said to “collapse.” Margins are adjoining if there are no nonempty content, padding or border areas or clearance to separate them.

For example, in the following fragment with the given style rules:

p { display: block; margin: 2em 0 1em 0 }
div { display: block; margin: 2.5em 0 }
...
<p>First paragraph</p>
<div>
  <p>Second paragraph</p>
</div>

the bottom margin of the first p (=1em), the top margin of the div (=2.5em) and the top margin of the second p (=2em) collapse. The result is a single margin of 2.5em (the maximum of the three) between the bottom of the first p and the top of the second.

[add image]

In the following fragment,

p { display: block; margin: 2em 0 1em 0 }
div { display: block; margin: 2.5em 0;
      border: thin solid }
...
<p>First paragraph</p>
<div>
  <p>Second paragraph</p>
</div>

the bottom margin of the first p and the top margin of the div collapse, but the top margin of the second p does not collapse with them, because it is not adjoining; the border of the div separates them.

[add image]

If a set of adjoining margins collapses, then the width of the resulting margin is M - N, where M is the maximum of the adjoining margins that are positive, or zero if there are none; and N is the minimum of the adjoining margins that are negative, or zero if there are none.

We call an element or box collapsed through if two of its margins collapse with each other.

The most common use of collapsing through elements is that empty paragraphs don't cause extra white space:

<p>First paragraph
<p>Second paragraph
<p>
<p>Last paragraph

There is equal space between the first and second paragraphs as between the second and last.

The following two sets of rules determine which margins collapse.

  • Only margins of block-level boxes can collapse.
  • Margins of a floated box do not collapse with any other margins.
  • Margins of a box with ‘overflow’ other than ‘visible’ do not collapse with its children's margins.
  • Margins of an absolutely positioned box (see [CSS3POS]) do not collapse with any other margins.
  • Margins of an ‘inline-block’ box do not collapse (not even with its in-flow children). Assuming the first rule above (“only block-level”) is correct, this rule seems redundant, because an inline block is not block-level.
  • Margins of the root element's box do not collapse.
  • If a box is collapsed through and it has clearance applied to one of the collapsed margins, then those margins do not collapse with certain of the parent's margins: If clearance is applied to, respectively, the top, right or left margin, then those margins do not collapse with the parent's bottom, left or right margin, respectively.

Except when forbidden by the list above, the following margins collapse:

  • If a margin P collapses with a margin Q and margin Q with a margin R, then P, Q and R collapse together. (“Collapsing is transitive”)

  • The top margin of a box A collapses with the top margin of its parent box B if the margins are adjoining and B is ‘tb’.

    Note that A itself may be vertical box.

  • The bottom margin of a box A collapses with the bottom margin of its parent box B if the margins are adjoining and B is ‘tb’.

  • The left margin of a box A collapses with the left margin of its parent box B if the margins are adjoining and B is ‘rl’ or ‘lr’.

  • The right margin of a box A collapses with the right margin of its parent box B if the margins are adjoining and B is ‘rl’ or ‘lr’.

  • The top margin of a box A collapses with the bottom margin of a sibling box B if the margins are adjoining and their parent is ‘tb’.

  • A right margin of a box A collapses with the left margin of a sibling box B if the margins are adjoining and their parent is ‘rl’ or ‘lr’.

  • The top and bottom margins of a box A collapse if the margins are adjoining and the box is ‘tb’. (The box is “collapsed through.”)

    In this case, the position of the element depends on its relationship with the other elements whose margins are being collapsed.

    • If the box A's margins are collapsed with its parent's top margin, the top border edge of A is defined to be the same as the parent's.
    • Otherwise, either the parent is not taking part in the margin collapsing, or only the parent's bottom margin is involved. The position of A's top border edge is the same as it would have been if A had a nonzero top border.

    Note that the positions of elements that have been collapsed through have no effect on the positions of the other elements with whose margins they are being collapsed; the top border edge position is only required for laying out descendants of these elements.

  • The left and right margins of a box A collapse (“collapse through”) if the margins are adjoining and the box is ‘rl’ or ‘lr’.

    In this case, the position of the element depends on its relationship with the other elements whose margins are being collapsed.

    • If A's parent is ‘rl’:
      • If A's margins are collapsed with its parent's right margin, the right border edge of A is defined to be the same as the parent's.
      • Otherwise (i.e., either the element's parent is not taking part in the margin collapsing, or only the parent's left margin is involved), the position of A's right border edge is the same as it would have been if A had a nonzero top border.
    • If A's parent is ‘lr’:
      • If A's margins are collapsed with its parent's left margin, the left border edge of A is defined to be the same as the parent's.
      • Otherwise (i.e., either the element's parent is not taking part in the margin collapsing, or only the parent's right margin is involved),, the position of A's left border edge is the same as it would have been if A had a nonzero left border.

In a horizontal flow, the bottom margin of an in-flow block-level element is always adjoining to the top margin of its next in-flow block-level sibling, unless that sibling has clearance:

<p style="margin-bottom: 2em">The bottom margin of this
box…</p>

<p style="margin-top: 3em">… collapses with the top margin
of this box, to yield max(2em, 3em) = 3em margin.</p>

The top margin of an in-flow block-level element is adjoining to its first in-flow block-level child's top margin if the element has no top border, no top padding, and the child has no clearance:

<div style="margin-top: 2em; padding: 0; border: 0">
  <p style="margin-top: 3em">
    The top margin of the DIV and the P
    collapse, to yield max(2em, 3em) = 3em margin.
  </p>
</div>

The bottom margin of an in-flow block-level element with a ‘height’ of ‘auto’ and ‘min-height’ less than the element's used height and ‘max-height’ greater than the element's used height is adjoining to its last in-flow block-level child's bottom margin if the element has no bottom padding or border:

<div style="margin-bottom: 2em; padding: 0; border: 0;
    height: auto; min-height: 0; max-height: 100em">
  <p style="margin-bottom: 3em">
    The bottom margin of the DIV and the P collapse, to yield max(2em,
    3em) = 3em margin.
  </p>
</div>

An element's own margins are adjoining if the ‘min-height’ property is zero, and it has neither vertical borders nor vertical padding, and it has a ‘height’ of either 0 or ‘auto’, and it does not contain a line box, and all of its in-flow children's margins (if any) are adjoining:

<div style="margin-top: 2em; margin-bottom: 3em">
  <p style="position: absolute">
    The DIV is empty and its top and bottom margins collapse.
  </p>
</div>

When an element's own margins collapse, and that element has had clearance applied to it, its top margin collapses with the adjoining margins of subsequent siblings but that resulting margin does not collapse with the bottom margin of the parent block:

<div style="margin-bottom: 2em">
  <p style="float: left">
    The margins of the next two Ps collapse
  <p style="clear: left; margin-top: 4em; margin-bottom: 3em">

  </p>
  <p style="margin-top: 1em; margin-bottom: 1em">

  </p>
</div>

The top and bottom margins of the two empty Ps collapse all together. But they can't collapse with the bottom of the DIV, because one of the two empty P's has clearance.

Check this. This is probably the only possible interpretation of the rules, but it is certainly not obvious that the clearance of one element may stop later elements from collapsing…

Collapsing is based on the used value of ‘padding’, ‘margin’, and ‘border’ (i.e., after resolving any percentages). The collapsed margin is calculated over the used value of the various margins.

7. The ‘width’ and ‘height’ properties

Name: | width
Value: | <length> | <percentage> | auto
Initial: | auto
Applies to: | all elements but non-replaced inline elements, table rows, and row groups
Inherited: | no
Percentages: | refer to width of containing block
Media: | visual
Computed value: | the percentage or ‘auto’ as specified or the absolute length; ‘auto’ if the property does not apply
Name: | height
Value: | <length> | <percentage> | auto
Initial: | auto
Applies to: | all elements but non-replaced inline elements, table columns, and column groups
Inherited: | no
Percentages: | see prose
Media: | visual
Computed value: | the percentage or ‘auto’ (see prose under <percentage>) or the absolute length; ‘auto’ if the property does not apply

These properties specify the width and height of the content area, padding area or border area (depending on ‘box-sizing’) of certain boxes.

Values have the following meanings:

<length>
Specifies the width of the content area using a length unit.
<percentage>
Specifies a percentage width. The percentage is calculated with respect to the width of the generated box's containing block. If the containing block's width depends on this element's width, then the resulting layout is undefined in CSS3.
auto
The width depends on the values of other properties. See the sections below.

Do we want to define unknown percentages in CSS3? Something simple, such as ‘auto’, or something more fancy, such as trying to solve percentages?

Negative values are illegal.

For example, the following rule fixes the content width of paragraphs at 100 px:

p { width: 100px }

8. The ‘min-width’, ‘max-width’, ‘min-height’ and ‘max-height’ properties

Name: | min-width, min-height
Value: | <length> | <percentage> | inherit
Initial: | 0
Applies to: | all elements but non-replaced inline elements, table rows, and row groups
Inherited: | no
Percentages: | refer to width, resp. height of containing block
Media: | visual
Computed value: | the percentage as specified or the absolute length
Name: | max-width, max-height
Value: | <length> | <percentage> | none
Initial: | none
Applies to: | all elements but non-replaced inline elements, table rows, and row groups
Inherited: | no
Percentages: | refer to width, resp. height of containing block
Media: | visual
Computed value: | the percentage as specified or the absolute length or ‘none’

These properties allow authors to constrain content widths and heights to a certain range. Values have the following meanings:

<length>
Specifies a fixed minimum or maximum for ‘width’ or ‘height’.
<percentage>
Specifies a minimum or maximum for ‘width’ or ‘height’ as a percentage of the corresponding dimension of the containing block. If that containing block's dimension is negative, the used value is zero. If that containing block's dimension depends on this element's dimension, then the resulting layout is undefined. Or: use the initial value?
none
No limit on the width or height of the box.

Negative values are illegal.

9. Calculating widths, heights and margins

The following two algorithms define the used value of ‘width’ and ‘height’ respectively and also the used values of the ‘margin’ properties and of ‘top’, ‘right’ ‘bottom’ and ‘left’.

Note that they do not affect the computed values of ‘width’ and ‘height’. Also note that in some cases the used width has to be known in order to calculate the used height, or vice versa,

For ‘width’:

  1. The tentative used width is calculated (without ‘min-width’, and ‘max-width’) following the rules in the subsections below.
  2. If the tentative used width is greater than ‘max-width’, the same rules are applied again, but this time using the computed value of ‘max-width’ as the computed value for 'width.
  3. If the resulting width is smaller than ‘min-width’, the same rules are applied again, but this time using the computed value of ‘min-width’ as the computed value for ‘width’.

For ‘height’:

  1. The tentative used height is calculated (without ‘min-height’, and ‘max-height’) following the rules under “Calculating widths, heights and margins” below.
  2. If the tentative used height is greater than ‘max-height’, the same rules are applied again, but this time using the computed value of ‘max-height’ as the computed value for 'height.
  3. If the resulting height is smaller than ‘min-height’, the same rules are applied again, but this time using the computed value of ‘min-height’ as the computed value for ‘height’.

However, for replaced elements with an intrinsic ratio and both ‘width’ and ‘height’ specified as ‘auto’, the algorithm is as follows:

Select from the table the resolved height and width values for the appropriate constraint violation. Take the max-width and max-height as max(min, max) so that min ≤ max holds true. In this table w and h stand for the results of the width and height computations ignoring the ‘min-width’, ‘min-height’, ‘max-width’ and ‘max-height’ properties. Normally these are the intrinsic width and height, but they may not be in the case of replaced elements with intrinsic ratios.

Constraint violation | Resolved width | Resolved height
none | w | h
w > max-width | max-width | max(max-width * h/w, min-height)
w < min-width | min-width | min(min-width * h/w, max-height)
h > max-height | max(max-height * w/h, min-width) | max-height
h < min-height | min(min-height * w/h, max-width) | min-height
(w > max-width) and (h > max-height), where (max-width/w ≤ max-height/h) | max-width | max(min-height, max-width * h/w)
(w > max-width) and (h > max-height), where (max-width/w > max-height/h) | max(min-width, max-height * w/h) | max-height
(w < min-width) and (h < min-height), where (min-width/w ≤ min-height/h) | min(max-width, min-height * w/h) | min-height
(w < min-width) and (h < min-height), where (min-width/w > min-height/h) | min-width | min(max-height, min-width * h/w)
(w < min-width) and (h > max-height) | min-width | max-height
(w > max-width) and (h < min-height) | max-width | min-height

Then apply the appropriate rules in the subsections below, as if ‘width’ and ‘height’ were computed as these values.

Note that some values of the ‘image-scaling’ property ([CSS3PAGE]) may further change the used values of ‘width’ and ‘height’.

The following subsections apply if the element's containing block is horizontal. If it is vertical, the same rules apply, but with every occurrence of “left” replaced by “top,” “right” by “bottom,” “top” by “right,” “bottom” by “left”, “height” by “width” and “width” by “height.”

9.1. Inline, non-replaced elements

The ‘width’ and ‘height’ properties do not apply. For each of ‘left’, ‘right’, ‘top’, ‘bottom’, ‘margin-left’, ‘margin-right’, ‘margin-top’ and ‘margin-bottom’, the used value is equal to the computed value, except that a computed value of ‘auto’ becomes a used value of ‘0’.

Note that this section applies equally when the containing block is horizontal as when it is vertical.

9.2. Inline or floating, replaced elements

The used values of ‘margin-left’, ‘margin-right’, ‘margin-top’ and ‘margin-bottom’ are equal to the computed value, except that a computed value of ‘auto’ becomes a used value of ‘0’.

If ‘height’ and ‘width’ both have computed values of ‘auto’ and the element also has an intrinsic width, then that intrinsic width is the used value of ‘width’.

If ‘height’ and ‘width’ both have computed values of ‘auto’ and the element also has an intrinsic height, then that intrinsic height is the used value of ‘height’.

If ‘height’ and ‘width’ both have computed values of ‘auto’ and the element has no intrinsic width, but does have an intrinsic height and intrinsic ratio; or if ‘width’ has a computed value of ‘auto’, ‘height’ has some other computed value, and the element has an intrinsic ratio; then the used value of ‘width’ is:

(used height) * (intrinsic ratio)

If ‘height’ and ‘width’ both have computed values of ‘auto’ and the element has no intrinsic height, but does have an intrinsic width and intrinsic ratio; or if ‘height’ has a computed value of ‘auto’, ‘width’ has some other computed value, and the element has an intrinsic ratio; then the used value of ‘height’ is:

(used width) / (intrinsic ratio)

If ‘height’ and ‘width’ both have computed values of ‘auto’ and the element has an intrinsic ratio but no intrinsic height or width and the containing block's width doesn't itself depend on the replaced element's width, then the used value of ‘width’ is calculated from the constraint equation used for block-level, non-replaced elements in normal flow. The used value for ‘height’ is: (used width) / (intrinsic ratio).

If ‘width’ has a computed value of ‘auto’, but none of the conditions above are met, then the used value of ‘width’ becomes 300px. If 300px is too wide to fit the device, UAs should use the width of the largest rectangle that has a 2:1 ratio and fits the device instead.

If ‘height’ has a computed value of ‘auto’ and none of the rules above define its used value, then the used value of ‘height’ must be set to the height of the largest rectangle that has a 2:1 ratio, has a height not greater than 150px, and has a width not greater than the device width.

Theoretically, a device may be wider than than 300px but not tall enough for 150px. In that case the resulting replaced element will be too tall. But this is the formulation in CSS 2.1 and it seems not worth improving such an edge case.

Percentage intrinsic widths are first evaluated with respect to the containing block's width, if that width doesn't itself depend on the replaced element's width. If it does, then a percentage intrinsic width on that element can't be resolved and the element is assumed to have no intrinsic width.

Note that this section applies equally when the containing block is horizontal as when it is vertical.

9.3. Block-level, non-replaced elements in normal flow when ‘overflow’ computes to ‘visible’

This section also applies to block-level non-replaced elements in normal flow when ‘overflow’ does not compute to ‘visible’ but has been propagated to the viewport.

The following constraints must hold among the used values of the properties.

‘margin-left’ + ‘border-left-width’ + ‘padding-left’ + ‘width’ + ‘padding-right’ + ‘border-right-width’ + ‘margin-right’ + scrollbar width (if any) = width of containing block

If ‘width’ is not ‘auto’ and ‘border-left-width’ + ‘padding-left’ + ‘width’ + ‘padding-right’ + ‘border-right-width’ + scrollbar width (if any) (plus any of ‘margin-left’ or ‘margin-right’ that are not ‘auto’) is larger than the width of the containing block, then any ‘auto’ values for ‘margin-left’ or ‘margin-right’ are, for the following rules, treated as zero. We should drop this paragraph. It causes blocks that are wider than their parent not to be centered (unlike blocks that are narrower), which looks strange.

All the above properties that have a computed value other than ‘auto’ have a used value equal to the computed value, except if they all have a computed value other than ‘auto’. Then the values are said to be “over-constrained” and one of the used values will have to be different from its computed value. If the ‘direction’ property of the containing block has the value ‘ltr’, the specified value of ‘margin-right’ is ignored and the value is calculated so as to make the equality true. If the value of ‘direction’ is ‘rtl’, this happens to ‘margin-left’ instead.

If there is exactly one value specified as ‘auto’, its used value follows from the equality.

If ‘width’ is set to ‘auto’, any other ‘auto’ values become ‘0’ and ‘width’ follows from the resulting equality.

If both ‘margin-left’ and ‘margin-right’ are ‘auto’, their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

The “scrollbar width” value is only relevant if the user agent uses a scrollbar as its scrolling mechanism. See the definition of the ‘overflow’ property.

If ‘margin-top’, or ‘margin-bottom’ are ‘auto’, their used value is 0. If ‘height’ is ‘auto’, the height depends on whether the element has any block-level children and whether it has padding or borders:

If it only has inline-level children, the height is the distance between the top of the topmost line box and the bottom of the bottommost line box.

If it has block-level children, the height is the distance between the top border-edge of the topmost block-level child box that doesn't have margins collapsed through it and the bottom border-edge of the bottommost block-level child box that doesn't have margins collapsed through it. However, if the element has a nonzero top padding and/or top border, or is the root element, then the content starts at the top margin edge of the topmost child. (The first case expresses the fact that the top and bottom margins of the element collapse with those of the topmost and bottommost children, while in the second case the presence of the padding/border prevents the top margins from collapsing.) Similarly, if the element has a nonzero bottom padding and/or bottom border, then the content ends at the bottom margin edge of the bottommost child.

Only children in the normal flow are taken into account (i.e., floating boxes and absolutely positioned boxes are ignored, and relatively positioned boxes are considered without their offset). Note that the child box may be an anonymous block box.

9.4. Other block-level, non-replaced elements in normal flow

POWERED BY HeroNote

This section applies to block-level, non-replaced elements when ‘overflow’ does not compute to ‘visible’ (except if the ‘overflow’ property's value has been propagated to the viewport).

Apply the rules for block-level, non-replaced elements in normal flow, but ignore the resulting values for ‘height’, ‘margin-top’ and ‘margin-bottom’.

If ‘margin-top’, or ‘margin-bottom’ are ‘auto’, their used value is 0. If ‘height’ is ‘auto’, its used value is defined by “‘Auto’ heights for flow roots.”

9.5. ‘Inline-block’ or floating, non-replaced elements

The used values of ‘margin-left’, ‘margin-right’, ‘margin-top’ and ‘margin-bottom’ are their computed values, except that a computed value of ‘auto’ gives a used value of 0.

The used value of ‘width’ is the computed value, unless that is ‘auto’, when used value is the shrink-to-fit width.

The used value of ‘height’ is the computed value, unless that is ‘auto’, when the used value is defined by “‘Auto’ heights for flow roots.”

For inline-block boxes, the margin box is used when calculating the height of the line box. Does this belong here?

9.6. Absolutely positioned, non-replaced elements

For the purposes of this section and the next, the term static position (of an element) refers, roughly, to the position an element would have had in the normal flow. More precisely:

  • The static position for ‘left’ is the distance from the left edge of the containing block to the left margin edge of a hypothetical box that would have been the first box of the element if its ‘position’ property had been ‘static’ and ‘float’ had been ‘none’. The value is negative if the box's margin is to the left of the containing block's edge.
  • The static position for ‘right’ is the distance from the right edge of the containing block to the right margin edge of the same hypothetical box as above. The value is positive if the box's margin is to the left of the containing block's edge.
  • The static position for ‘top’ is the distance from the top edge of the containing block to the top margin edge of the same hypothetical box as above. The value is negative if the box's margin is above the containing block's edge.
  • The static position for ‘bottom’ is the distance from the bottom edge of the containing block to the bottom margin edge of the same hypothetical box as above. The value is positive if the box's margin is above the containing block's edge.

But rather than actually calculating the dimensions of that hypothetical box, user agents are free to make a guess at its probable position.

For the purposes of calculating the static position, the containing block of fixed positioned elements is the initial containing block instead of the viewport, and all scrollable boxes should be assumed to be scrolled to their origin.

This constraint must hold among the used values:

‘left’ + ‘margin-left’ + ‘border-left-width’ + ‘padding-left’ + ‘width’ + ‘padding-right’ + ‘border-right-width’ + ‘margin-right’ + ‘right’ + scrollbar width (if any) = width of containing block

If all three of ‘left’, ‘width’, and ‘right’ are ‘auto’: First set any ‘auto’ values for ‘margin-left’ and ‘margin-right’ to 0. Then, if the ‘direction’ property of the containing block is ‘ltr’ set ‘left’ to the static position and apply rule number three below; otherwise, set ‘right’ to the static position and apply rule number one below.

If none of the three is ‘auto’: If both ‘margin-left’ and ‘margin-right’ are ‘auto’, solve the equation under the extra constraint that the two margins get equal values, unless this would make them negative, in which case when direction of the containing block is ‘ltr’ (‘rtl’), set ‘margin-left’ (‘margin-right’) to zero and solve for ‘margin-right’ (‘margin-left’). Should we remove the phrase starting with “unless”? If one of ‘margin-left’ or ‘margin-right’ is ‘auto’, solve the equation for that value. If the values are over-constrained, ignore the value for ‘left’ (in case the ‘direction’ property of the containing block is ‘rtl’) or ‘right’ (in case ‘direction’ is ‘ltr’) and solve for that value.

Otherwise, set ‘auto’ values for ‘margin-left’ and ‘margin-right’ to 0, and pick the one of the following six rules that applies.

  1. ‘left’ and ‘width’ are ‘auto’ and ‘right’ is not ‘auto’, then the width is shrink-to-fit. Then solve for ‘left’.
  2. ‘left’ and ‘right’ are ‘auto’ and ‘width’ is not ‘auto’, then if the ‘direction’ property of the containing block is ‘ltr’ set ‘left’ to the static position, otherwise set ‘right’ to the static position. Then solve for ‘left’ (if ‘direction is ’'rtl‘) or ‘right’ (if ‘direction’ is ’ltr'').
  3. ‘width’ and ‘right’ are ‘auto’ and ‘left’ is not ‘auto’, then the width is shrink-to-fit. Then solve for ‘right’.
  4. ‘left’ is ‘auto’, ‘width’ and ‘right’ are not ‘auto’, then solve for ‘left’.
  5. ‘width’ is ‘auto’, ‘left’ and ‘right’ are not ‘auto’, then solve for ‘width’.
  6. ‘right’ is ‘auto’, ‘left’ and ‘width’ are not ‘auto’, then solve for ‘right’.

This constraint must also hold among the used values:

‘top’ + ‘margin-top’ + ‘border-top-width’ + ‘padding-top’ + ‘height’ + ‘padding-bottom’ + ‘border-bottom-width’ + ‘margin-bottom’ + ‘bottom’ + scrollbar height (if any) = height of containing block

If all three of ‘top’, ‘height’, and ‘bottom’ are ‘auto’, set ‘top’ to the static position and apply rule number three below.

If none of the three are ‘auto’: If both ‘margin-top’ and ‘margin-bottom’ are ‘auto’, solve the equation under the extra constraint that the two margins get equal values. If one of ‘margin-top’ or ‘margin-bottom’ is ‘auto’, solve the equation for that value. If the values are over-constrained, ignore the value for ‘bottom’ and solve for that value.

Otherwise, pick the one of the following six rules that applies.

  1. ‘top’ and ‘height’ are ‘auto’ and ‘bottom’ is not ‘auto’: The used value of ‘bottom’ is its computed value. The used height is defined by “‘Auto’ heights for flow roots.” The used values of ‘margin-top’ and ‘margin-bottom’ are their computed values, except that any ‘auto’ gives a used value of 0. Finally, the constraint gives the used value of ‘top’.
  2. ‘top’ and ‘bottom’ are ‘auto’ and ‘height’ is not ‘auto’: The used value of ‘top’ is its static position. The used values of ‘margin-top’ and ‘margin-bottom’ are their computed values, except that any ‘auto’ gives a used value of 0. Finally, the constraint gives the used value for ‘bottom’.
  3. ‘height’ and ‘bottom’ are ‘auto’ and ‘top’ is not ‘auto’: The used height is defined by “‘Auto’ heights for flow roots.” The used values of ‘margin-top’ and ‘margin-bottom’ are their computed values, except that any ‘auto’ gives a used value of 0. Finally, the constraint gives the used value of ‘bottom’.
  4. ‘top’ is ‘auto’, ‘height’ and ‘bottom’ are not ‘auto’: The used values of ‘margin-top’ and ‘margin-bottom’ are their computed values, except that any ‘auto’ gives a used value of 0. The constraint gives the used value for ‘top’.
  5. ‘height’ is ‘auto’, ‘top’ and ‘bottom’ are not ‘auto’: The used values of ‘margin-top’ and ‘margin-bottom’ are their computed values, except that any ‘auto’ gives a used value of 0. The constraint gives the used value for ‘height’.
  6. ‘bottom’ is ‘auto’, ‘top’ and ‘height’ are not ‘auto’: The used values of ‘margin-top’ and ‘margin-bottom’ are their computed values, except that any ‘auto’ gives a used value of 0. The constraint gives the used value for ‘bottom’.

The “scrollbar height” and “scrollbar width” values are only relevant if the user agent uses a scrollbar as its scrolling mechanism. See the definition of the ‘overflow’ property.

9.7. Absolutely positioned, replaced elements

This situation is similar to the previous one, except that the element may have an intrinsic size or ratio. The sequence of substitutions is now:

  1. The used value of ‘width’ and ‘height’ is determined as for inline replaced elements.
  2. For each of ‘top’, ‘right’, ‘bottom’, ‘left’, ‘margin-top’, ‘margin-right’, ‘margin-bottom’ and ‘margin-left’, if the computed value is not ‘auto’, the used value is equal to the computed value.
  3. If both ‘left’ and ‘right’ have the value ‘auto’, then if ‘direction’ of the containing block is ‘ltr’, the used value of ‘left’ is its static position; else if ‘direction’ is ‘rtl’, the used value of ‘right’ is its static position.
  4. If both ‘top’ and ‘bottom’ have the value ‘auto’, then the used value of ‘top’ is its static position.
  5. If ‘left’ or ‘right’ (or both) are ‘auto’, and ‘margin-left’ is ‘auto’, then the used value of ‘margin-left’ is 0.
  6. If ‘left’ or ‘right’ (or both) are ‘auto’, and ‘margin-right’ is ‘auto’, then the used value of ‘margin-right’ is 0.
  7. If neither ‘left’ nor ‘right’ are ‘auto’ and both ‘margin-left’ and ‘margin-right’ are ‘auto’, then the used values satisfy the extra constraint that ‘margin-right’ and ‘margin-left’ are equal, unless this would make them negative, in which case when the direction of the containing block is ‘ltr’ (‘rtl’), the used value of ‘margin-left’ (‘margin-right’) is 0. Remove the part starting with “unless”? It looks better to center the image.

The remaining used values, if any, follows from these two constraints:

‘left’ + ‘margin-left’ + ‘border-left-width’ + ‘padding-left’ + ‘width’ + ‘padding-right’ + ‘border-right-width’ + ‘margin-right’ + ‘right’ + scrollbar width (if any) = width of containing block

‘top’ + ‘margin-top’ + ‘border-top-width’ + ‘padding-top’ + ‘height’ + ‘padding-bottom’ + ‘border-bottom-width’ + ‘margin-bottom’ + ‘bottom’ + scrollbar height (if any) = height of containing block

If the first equation is over-constrained, ignore the value for either ‘left’ (in case the ‘direction’ property of the containing block is ‘rtl’) or ‘right’ (in case ‘direction’ is ‘ltr’) and solve for that value.

If the second equation is over-constrained, ignore the value for ‘bottom’ and solve for that value.

9.8. Block-level, replaced elements in normal flow

Apply the rules for inline replaced elements, but ignore the resulting values for ‘margin-left’ and ‘margin-right’. To compute the used value of those, apply the rules for block-level, non-replaced elements using the used values just found for ‘width’, ‘border’ and ‘padding’ as if they were the computed values.

9.9. Floating, non-replaced elements

The used values of the margins are equal to the computed values, except that the used values of any margins computed as ‘auto’ are ‘0’.

The used value of ‘width’ is equal to the computed value, except that if ‘width’ is computed as ‘auto’, the used value is the shrink-to-fit width.

If the computed value of ‘height’ is not ‘auto’, the used value is the computed value. Otherwise the used height depends on the descendants, as defined in “‘Auto’ heights for flow roots.”

9.10. ‘Auto’ heights for flow roots

In certain cases (see the preceding sections), the height of an element is computed as follows:

If it only has inline-level children, the height is the distance between the top of the topmost line box and the bottom of the bottommost line box.

If it has block-level children, the height is the distance between the top margin-edge of the topmost block-level child box and the bottom margin-edge of the bottommost block-level child box.

Absolutely positioned children are ignored, and relatively positioned boxes are considered without their offset. Note that the child box may be an anonymous block box.

In addition, if the element has any floating descendants whose bottom margin edge is below the bottom, then the height is increased to include those edges. Only floats that are children of the element itself or of descendants in the normal flow are taken into account, e.g., floats inside absolutely positioned descendants or other floats are not.

9.11. Shrink-to-fit

Calculation of the shrink-to-fit width is similar to calculating the width of a table cell using the automatic table layout algorithm. Roughly: calculate the preferred width by formatting the content without breaking lines other than where explicit line breaks occur, and also calculate the preferred minimum width, e.g., by trying all possible line breaks. CSS does not define the exact algorithm. Thirdly, find the available width: in this case, this is the width of the containing block minus the used values of ‘margin-left’, ‘border-left-width’, ‘padding-left’, ‘padding-right’, ‘border-right-width’, ‘margin-right’, and the widths of any relevant scroll bars.

Then the shrink-to-fit width is: min(max(preferred minimum width, available width), preferred width).

Define in more detail, using a text by David Baron.

10. Floating boxes

10.1. Introduction to floats

(This section is not normative.)

A float is a box that is shifted to the left or right on the current line. The most interesting characteristic of a float (or “floating” box) is that content may flow along its side (or be prohibited from doing so by the ‘clear’ property). Content flows down the right side of a left-floated box and down the left side of a right-floated box. The following is a (non-normative) introduction to float positioning and content flow; the exact rules governing float positioning are given in the next section.

A floated box is shifted to the left or right until its outer edge touches the containing block edge or the outer edge of another float. If there is a line box, the top of the floated box is aligned with the top of the current line box.

If there isn't enough horizontal room for the float, it is shifted downward until either it fits or there are no more floats present.

Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float didn't exist. However, line boxes created next to the float are shortened to make room for the margin box of the float. If a shortened line box is too small to contain any further content, then it is shifted downward until either it fits or there are no more floats present. Any content in the current line before a floated box is re-flowed in the first available line on the other side of the float. In other words, if inline boxes are placed on the line before a left float is encountered that fits in the remaining line box space, the left float is placed on that line, aligned with the top of the line box, and then the inline boxes already on the line are moved accordingly to the right of the float (the right being the other side of the left float) and vice versa for rtl and right floats.

In the following document fragment, the containing block is too narrow to contain the content next to the float, so the content gets moved to below the floats where it is aligned in the line box according to the text-align property.

p { width: 10em; border: solid aqua; }
span { float: left; width: 5em; height: 5em; border: solid blue; }

...

<p>
  <span> </span>
  Supercalifragilisticexpialidocious
</p>

This fragment might look like this:

Image illustrating the effect of an unbreakable piece of content being reflowed to just after a float which left insufficient room next to it for the content to fit.

The text is too long to fit in a shortened line box next to the float (dark blue box) and so it is pushed down until it is passed the float.

Several floats may be adjacent, and this model also applies to adjacent floats in the same line.

The following rule floats all IMG boxes with class="icon" to the left (and sets the left margin to ‘0’):

img.icon {
  float: left;
  margin-left: 0;
}

Consider the following HTML source and style sheet:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
  <HEAD>
    <TITLE>Float example</TITLE>
    <STYLE type="text/css">
      IMG { float: left }
      BODY, P, IMG { margin: 2em }
    </STYLE>
  </HEAD>
  <BODY>
    <P><IMG src=img.png alt="This image will illustrate floats">
       Some sample text that has no other...
  </BODY>
</HTML>

The IMG box is floated to the left. The content that follows is formatted to the right of the float, starting on the same line as the float. The line boxes to the right of the float are shortened due to the float's presence, but resume their “normal” width (that of the containing block established by the P element) after the float. This document might be formatted as:

Image illustrating how floating boxes interact with margins.

An image showing the various margins of the BODY, P and IMG element. Not that the top margin of the floating IMG does not collapse with the top margins of the P and BODY elements.

Formatting would have been exactly the same if the document had been:

<BODY>
  <P>Some sample text
  <IMG src=img.png alt="This image will illustrate floats">
           that has no other...
</BODY>

because the content to the left of the float is displaced by the float and re-flowed down its right side.

As stated in “Collapsing margins,” the margins of floating boxes never collapse with margins of adjacent boxes. Thus, in the previous example, vertical margins do not collapse between the P box and the floated IMG box.

The contents of floats are stacked as if floats generated new stacking contexts, except that any elements that actually create new stacking contexts take part in the float's parent's stacking context. A float can overlap other boxes in the normal flow (e.g., when a normal flow box next to a float has negative margins). When this happens, floats are rendered in front of non-positioned in-flow blocks, but behind in-flow inlines.

Here is another illustration, showing what happens when a float overlaps borders of elements in the normal flow.

Image showing a floating image that overlaps the borders of two paragraphs: the borders are interrupted by the image.

A floating image obscures borders of block boxes it overlaps.

The following example illustrates the use of the ‘clear’ property to prevent content from flowing next to a float.

Assuming a rule such as this:

p { clear: left }

formatting might look like this:

Image showing a floating image and the effect of 'clear: left' on the two paragraphs.

Both paragraphs have set ‘clear: left’, which causes the second paragraph to be “pushed down” to a position below the float – “clearance” is added above its top margin to accomplish this (see the ‘clear’ property).

10.2. The ‘float’ property

Name: | float
Value: | left | right | none | <page-floats>
Initial: | none
Applies to: | all, but see 9.7
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified

This property specifies whether a box should float to the left, right, or not at all. It may be set for any element, but only applies to elements that generate boxes that are not absolutely positioned. The values of this property have the following meanings:

left
...
right
...
none
...
<page-floats>
See Generated Content for Paged Media [CSS3GCPM].

10.3. Rules for positioning floats

[To do: copy from CSS2 [CSS21] and generalize to vertical text]

Note that a box with a value of ‘float’ other than ‘none’ is a flow root.

The border box of a table, a block-level replaced element, or an element in the normal flow that is a flow root (such as an element with ‘overflow’ other than ‘visible’) must not overlap any floats in the same flow as the element itself. If necessary, implementations should clear the said element by placing it below any preceding floats, but may place it adjacent to such floats if there is sufficient space, by increasing one margin and decreasing the opposite margin. (“Sufficient space” means that the opposite margin does not become negative.)

10.4. The ‘clear’ property

Name: | clear
Value: | none | left | right | both
Initial: | none
Applies to: | block-level elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified

[To do: copy from CSS2 [CSS21] and generalize to vertical text]

11. Overflow

11.1. The ‘overflow’, ‘overflow-x’ and ‘overflow-y’ properties

In the preceding sections, several things (such as flow roots) depend on the value of ‘overflow’. We probably need to rewrite them in terms of “overflow-x and/or -y” or similar.

Name: | overflow-x, overflow-y,
Value: | visible | hidden | scroll | auto | no-display | no-content
Initial: | visible
Applies to: | non-replaced block-level elements and non-replaced ‘inline-block’ elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified, except ‘visible’, see text
Name: | overflow
Value: | [ visible | hidden | scroll | auto | no-display | no-content ]{1,2}
Initial: | see individual properties
Applies to: | non-replaced block-level elements and non-replaced ‘inline-block’ elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified, except ‘visible’, see text

These properties specify whether content is clipped when it overflows the element's content area. It affects the clipping of all of the element's content except any descendant elements (and their respective content and descendants) whose containing block is the viewport or an ancestor of the element. ‘Overflow-x’ determines clipping at the left and right edges, ‘overflow-y’ at the top and bottom edges.

‘Overflow’ is a shorthand. If it has one keyword, it sets both ‘overflow-x’ and ‘overflow-y’ to that keyword; if it has two, it sets ‘overflow-x’ to the first and ‘overflow-y’ to the second. Keywords have the following meanings:

visible
This value indicates that content is not clipped, i.e., it may be rendered outside the content box.
hidden
This value indicates that the content is clipped and that no scrolling mechanism should be provided to view the content outside the clipping region.
scroll
This value indicates that the content is clipped and that if the user agent uses a scrolling mechanism that is visible on the screen (such as a scroll bar or a panner), that mechanism should be displayed for a box whether or not any of its content is clipped. This avoids any problem with scrollbars appearing and disappearing in a dynamic environment. When this value is specified and the target medium is ‘print’, overflowing content may be printed.
auto
The behavior of the ‘auto’ value is UA-dependent, but should cause a scrolling mechanism to be provided for overflowing boxes.
no-display
When the content doesn't fit in the content box, the whole box is removed, as if ‘display: none’ were specified. [This idea is due to Till Halbach <tillh@opera.com>, July 21, 2005]
no-content
When the content doesn't fit in the content box, the whole content is hidden, as if ‘visibility: hidden’ were specified. [This idea is due to Till Halbach <tillh@opera.com>, July 21, 2005]

Even if ‘overflow’ is set to ‘visible’, content may be clipped to a UA's document window by the native operating environment.

UAs must apply the ‘overflow’ property set on the root element to the viewport. HTML UAs must instead apply the ‘overflow’ property from the BODY element to the viewport, if the value on the HTML element is ‘visible’. The ‘visible’ value when used for the viewport must be interpreted as ‘auto’. The element from which the value is propagated must have a used value for ‘overflow’ of ‘visible’.

The para above is from CSS 2.1. Need to check if the introduction of overflow-x/y changes anything.

In the case of a scrollbar being placed on an edge of the element's box, it should be inserted between the inner border edge and the outer padding edge. The space taken up by the scrollbars affects the computation of the dimensions in the rendering model.

A UA may use multiple scrolling mechanisms at the same time. E.g., if content overflows both to the right and to the bottom, it may use a marquee effect for the overflow to the right and a scrollbar for the overflow to the bottom.

Note that a box with ‘overflow’ other than ‘visible’ is a flow root.

Consider the following example of a block quotation (<blockquote>) that is too big for its containing block (established by a <div>). Here is the source:

<div>
<blockquote>
<p>I didn't like the play, but then I saw
it under adverse conditions - the curtain was up.</p>
<cite>- Groucho Marx</cite>
</blockquote>
</div>

Here is the style sheet controlling the sizes and style of the generated boxes:

div { width : 100px; height: 100px;
      border: thin solid red;
      }

blockquote   { width : 125px; height : 100px;
      margin-top: 50px; margin-left: 50px;
      border: thin dashed black
      }

cite { display: block;
       text-align : right;
       border: none
       }

The initial value of ‘overflow’ is ‘visible’, so the <blockquote> would be formatted without clipping, something like this:

[image: Rendered overflow]

Possible rendering with ‘overflow: visible’

Setting ‘overflow’ to ‘hidden’ for the <div>, on the other hand, causes the <blockquote> to be clipped by the containing block:

[image: Rendered overflow]

Possible rendering with ‘overflow: hidden’

A value of ‘scroll’ would tell UAs that support a visible scrolling mechanism to display one so that users could access the clipped content.

Consider this case where an absolutely positioned element is mixed with an overflow parent. Style sheet:

container { position: relative; border: solid; }
scroller { overflow: scroll; height: 5em; margin: 5em; }
satellite { position: absolute; top: 0; }
body { height: 10em; }

Document fragment:

<container>
 <scroller>
  <satellite/>
  <body/>
 </scroller>
</container>

In this example, the “scroller” element will not scroll the “satellite” element, because the latter's containing block is outside the element whose overflow is being clipped and scrolled.

The combination of collapsing margins, ‘max-height’ and ‘overflow: auto’ can lead to subtle differences in implementations, unless special care is taken. A UA should assume that an element can be rendered without a scrolling mechanism first, perform all the collapsing of margins, and check that the content height is indeed less than the ‘max-height’. If it is not, the process is repeated under the assumption that a scrolling mechanism is needed.

In the following document fragment, the outer DIV has ‘height: auto’, but ‘max-height: 5em’. The inner DIV has large margins and would normally just fit:

...
    #d1 { overflow: auto; max-height: 5em }
    #d2 { margin: 2em; line-height: 1 }
...
<div id=d1>
  <div id=d2>
    This DIV has big margins.
  </DIV>
</DIV>

If we assume that d1 needs scroll bars, then the height of d1, including the single line of text and twice 2em of margins, adds up to 5em plus a scrollbar. Since that is greater than 5em, the maximum allowed height, it seems we made the right assumption and d1 indeed needs scrollbars.

However, we should have started by assuming that no scrollbars are needed. In that case the content height of d1 is exactly the maximum height of 5em, proving that the assumption was correct and d1 indeed should not have scrollbars.

The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as their specified values, except that some combinations with ‘visible’ are not possible: if one is specified as ‘visible’ and the other is ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if ‘overflow-y’ is the same; otherwise it is the pair of computed values of ‘overflow-x’ and ‘overflow-y’.

The scrolling mechanism depends on the UA. The most common mechanism is a scrollbar, but panners, hand cursors, page flickers, etc. are also possible. A value of ‘scroll’ would tell UAs that support a visible scrolling mechanism to display one so that users can access the clipped content. The ‘overflow-style’ property lets an author specify one or more preferred scrolling mechanism.

Note that ‘overflow-x’ and ‘overflow-y’ did not exist in CSS2.

Note that ‘text-overflow’ (see [CSS3TEXT]) can be used to give a visual indication where text has been clipped.

11.2. The ‘overflow-style’ property

Name: | overflow-style
Value: | auto | [scrollbar | panner | move | marquee] [, [scrollbar | panner | move | marquee]]*
Initial: | auto
Applies to: | same as ‘overflow’
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | as specified

This property specifies the preferred scrolling methods for elements that overflow (see the ‘overflow’ property.) The value is either ‘auto’, meaning no preference, or a list of methods in order of preference. The UA should use the first scrolling method in the list that it supports. If it supports none of them, it must act as if the value was ‘auto’.

A UA that support a certain scrolling mechanism may be able to support it only in certain cases. E.g., a UA may be able to use the marquee effect only in the horizontal direction (or the line progression direction), or it may be able to use a panner only if none of the ancestor boxes uses a panner.

scrollbar
Scrollbars are typically narrow strips inserted on one or two edges of an element and which often have arrows to click on and a “thumb” to drag up and down (or left and right) to move the contents of the element.
panner
A panner is typically a rectangle shown in one corner of the element, with a smaller rectangle inside. The larger rectangle represents all the available content of the element and the smaller one the visible part. The smaller rectangle can be moved around by the user to move the content of the element accordingly.
move
The value ‘move’ refers to a method where the user can move the content of the element directly (rather than indirectly by moving a scrollbar or a panner). Typically, the mouse pointer changes into a hand or a cross of four arrows to indicate that the user can drag the content around with the mouse. Sometimes the user needs to explicitly activate the move mode and in that case he often can use both dragging (with the mouse) and key events to move the content.
marquee
The marquee effect (value ‘marquee’) consists of the content moving autonomously, without any user events to control it. A user who waits long enough will eventually see all the content that overflows.

This specification does not define what scrollbars, panners or the visual indicators for the ‘move’ method look like. The ‘marquee’ method is further defined below.

Another idea is to make ‘overflow’ a shorthand for ‘overflow-style’ and overflow-policy, where overflow-policy has syntax “visible | hidden | scroll | auto” and ‘overflow’ has “<‘overflow-policy’> || <‘overflow-style’>”. Then it is possible to write, e.g., ‘overflow: auto marquee, scrollbar’.

We will probably want to introduce overflow-x and overflow-y in CSS3 to separate the policy in the two directions. In that case we may want:

  • overflow-style-x: auto | [scrollbar | panner | move | marquee] [, …]*
  • overflow-style-y ditto
  • overflow-policy-x: visible | hidden | scroll | auto
  • overflow-policy-y ditto
  • overflow-x: <overflow-style-x> || <overflow-policy-x>
  • overflow-y ditto
  • overflow: <overflow-x>

‘overflow’ is then a shorthand that sets -x and -y to the same value. (‘overflow: auto’ is ambiguous, as is ‘overflow: auto auto’, but it doesn't matter.)

11.3. The marquee properties

The marquee effect consists of the UA slowly moving the content of a box so that, over time, all parts of the box are visible at least once. The speed of the movement, whether the movement is in one direction only or back and forth, how far the content moves and how often may vary. But, unlike for most other scrolling mechanisms, these factors are not dependent on user events. Typically, marquee is used in contexts where there is no room for a scrollbar or other visible mechanism or when user interaction is limited: instead of actively moving hidden content into view with a scrollbar or similar mechanism, the user waits while the content moves by.

The following rules put the contents of each list item on a single line (unless it has hard line breaks) and causes the list items that are too wide to use a marquee effect (on UAs that support marquee):

li {overflow: auto; overflow-style: marquee; white-space: nowrap}

Name: | marquee-style
Value: | scroll | slide | alternate
Initial: | scroll
Applies to: | same as ‘overflow’
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified

The values are:

scroll
Start completely off one side, scroll all the way across and completely off.
slide
Start completely off one side, scroll in, and stop as soon as no more content is off that side.
alternate
Start with all overflow on one side, then scroll until there is no more overflow on that side. For the next loop, start with content overflowing on the other side (i.e., where the previous loop ended).

Is ‘bounce’ a better name than ‘alternate’?

The content of an element moves as one piece. E.g., if a element has two lines of text, both lines scroll together, even if only one of them overflows.

Name: | marquee-loop
Value: | <non-negative-integer> | infinite
Initial: | 1
Applies to: | same as ‘overflow’
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified

This property specifies how often the content moves. UAs should restart the loop count every time the element turns from completely invisible into (fully or partially) visible. E.g., an element that is outside the viewport starts moving when it is scrolled into view.

A UA may also take the visibility of the UA viewport itself into account, e.g., if the element is hidden behind a pop-up window or if the UA is iconified.

If ‘marquee-loop’ is different for different states of the element, e.g., ‘p {marquee-loop: 0} p:hover {marquee-loop: infinite}’, the loop counter must be reset each time the element enters a state with a different computed value.

For example, if the content of an li overflows under the following style rules, the content moves once when the li gets the focus or is hovered over. But, when it already has the focus when it is hovered over, the ‘marquee-loop’ property doesn't change and thus the content doesn't move again:

li {overflow: auto; overflow-style: marquee; marquee-loop: 0}
li:focus, li:hover {marquee-loop: 1}

Is ‘infinite’ a better default than ‘1’?

Name: | marquee-direction
Value: | forward | reverse
Initial: | reverse
Applies to: | same as ‘overflow’
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | ltr or rtl

This property determines the initial direction in which the content moves if the marquee effect is used. The actual direction depends on ‘direction’ and ‘block-progression’ as follows:

 |  | reverse | forward
tb | ltr | left | right
 | rtl | right | left
rl / lr | ltr | up | down
 | rtl | down | up

Note that ‘marquee-style: alternate’ moves content in the opposite direction on even-numbered loops.

Note that ‘reverse’ allows text to be read in the normal order. E.g., in English text (‘block-progression: tb’ and ‘direction: ltr’), text appears at the right edge, moves to the left and disappears at the left edge.

Name: | marquee-speed
Value: | slow | normal | fast
Initial: | normal
Applies to: | same as ‘overflow’
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified

This property determines how fast the content scrolls. The actual speed depends on the UA and the type of content. But, for a given UA and a given element, the following must always be true: slow < normal < fast.

12. The ‘visibility’ property

Name: | visibility
Value: | visible | hidden | collapse
Initial: | visible
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | as specified

This property specifies whether the boxes generated by an element are rendered. Invisible boxes still affect layout (set the ‘display’ property to ‘none’ to suppress box generation altogether). Values have the following meanings:

visible
The generated box is visible.
hidden
The generated box is invisible (fully transparent, nothing is drawn), but still affects layout. Furthermore, descendants of the element will be visible if they have ‘visibility: visible’.
collapse
See the Tables module [CSS3TBL]. If used on elements other than rows, row groups, columns, or column groups, ‘collapse’ has the same meaning as ‘hidden’.

13. Rotating boxes

Should probably be in the extended Box module instead of here…

Name: | rotation
Value: | <angle>
Initial: | 0
Applies to: | block-level elements, inline-table and inline-block
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | 0deg ≤ angle < 360deg
Name: | rotation-point
Value: | <bg-position>
Initial: | 50% 50%
Applies to: | block-level elements
Inherited: | no
Percentages: | Width and height of border box
Media: | visual
Computed value: | for <length> the absolute value, otherwise a percentage

The value of ‘rotation-point’ is a pair of values that defines a point as an offset from the top left border edge. Percentages refer to the width and height of the border box. Values may be negative.

‘Rotation’ rotates a block-level element counterclockwise around the point given by ‘rotation-point’. The border, padding and content are rotated, and also any background that is not ‘fixed’. All static or relatively positioned child elements (and their static and relatively positioned children, recursively) are rotated along. But absolutely positioned and fixed descendant elements are not.

Note that this means that rotation is relative. A child of a box that is rotated 45deg and that has a rotation of -45deg itself, actually ends up horizontal (but probably in a different location than when both rotations had been 0).

Rotation doesn't affect parent or sibling elements, they are laid out as if the element's rotation was 0. Conceptually, the element is first laid out without any rotation, then any relative positioning is applied to it (see [CSS3POS]) and finally any rotation. The rotation point is relative to the box after relative positioning.

Note that, like relative positioning, rotation can thus cause an element's box to overlap other boxes. It is the author's responsibility to give the element wide enough margins if such overlapping is not desired.

When a box is broken over several columns or pages, each of the boxes is rotated separately around its own rotation point.

The computed value of ‘rotation’ is the angle normalized to fall in 0deg ≤ angle < 360deg. The computed value or ‘rotation-point’ is a pair in which any <length> is made absolute, keywords are replaced by percentages and percentages are left as specified.

This example puts H1 elements upside down. It relies on the ‘rotation-point’ having its default value of ‘50% 50%’.

H1 {rotation: 180deg}

This example displays column headers in a table diagonally. It uses ‘block-progression’ (see [CSS3TEXTLAYOUT]) to write the column headers vertically and applies ‘rotation’ to rotate the headers 45 degrees to the left. A fairly wide padding is applied, to make sure the text of the headings doesn't overlap.

thead th {
    block-progression: rl;
    padding: 0.5em 1em;
    rotation: 45deg;
    rotation-point: bottom left }

Example of a table with rotated column headings.

In the table example, how are the borders rotated? Because the borders belong to two elements that are rotated individually.

Dave Hyatt proposes to generalize the property and call it “transform” with a syntax and functionality like in SVG, i.e., a property that accepts a series of transformations (rotations, translations, arbitrary affine transformations).

14. Stacking contexts

This section defines the painting order in more detail than described in the rest of the specification.

Definitions:

Tree Order
Preorder depth-first traversal of the rendering tree, in logical (not visual) order for bidirectional content, after taking into account properties that move boxes around such as the ‘run-in’ value of ‘display’.
Element
In this section, “element” refers to actual elements, pseudo-elements, and anonymous boxes. Pseudo-elements and anonymous boxes are treated as descendants in the appropriate places. For example, an outside list marker comes before an adjoining ‘:before’ box in the line box, which comes before the content of the box, and so forth.

The bottom of the stack is the furthest from the user, the top of the stack is the nearest to the user:

All layers are between the canvas and the user

Schematic diagram of a stacking context with four layers.

The stacking context background and most negative positioned stacking contexts are at the bottom of the stack, while the most positive positioned stacking contexts are at the top of the stack.

The canvas is transparent if contained within another, and given a UA-defined color if it is not. It is infinite in extent and contains the root element. Initially, the viewport is anchored with its top left corner at the canvas origin.

The stacking order for an element generating a stacking context (see the ‘z-index’ property) is:

  1. If the element is a root element:

    1. background color of element over the entire canvas.
    2. background image of element, over the entire canvas, anchored at the origin that would be used if it was painted for the root element.

  2. If the element is a block, list-item, or other block equivalent:

    1. background color of element unless it is the root element.
    2. background image of element unless it is the root element.
    3. border of element.

    Otherwise, if the element is a block level table:

    1. table backgrounds (color then image) unless it is the root element.
    2. column group backgrounds (color then image).
    3. column backgrounds (color then image).
    4. row group backgrounds (color then image).
    5. row backgrounds (color then image).
    6. cell backgrounds (color then image).
    7. all table borders (in tree order for separated borders).

  3. Stacking contexts formed by positioned descendants with negative z-indices (excluding 0) in z-index order (most negative first) then tree order.

  4. For all its in-flow, non-positioned, block-level descendants in tree order: If the element is a block, list-item, or other block equivalent:

    1. background color of element.
    2. background image of element.
    3. border of element.

    Otherwise, the element is a table:

    1. table backgrounds (color then image).
    2. column group backgrounds (color then image).
    3. column backgrounds (color then image).
    4. row group backgrounds (color then image).
    5. row backgrounds (color then image).
    6. cell backgrounds (color then image).
    7. all table borders (in tree order for separated borders).

  5. All non-positioned floating descendants, in tree order. For each one of these, treat the element as if it created a new stacking context, but any descendants which actually create a new stacking context should be considered part of the parent stacking context, not this new one.

  6. If the element is an inline element that generates a stacking context, then:

    1. For each line box that the element is in:
      1. Jump to 7.2.1 for the box(es) of the element in that line box (in tree order).

  7. Otherwise: first for the element, then for all its in-flow, non-positioned, block-level descendants in tree order:

    1. If the element is a block-level replaced element, then: the replaced content, atomically.

    2. Otherwise, for each line box of that element:

      1. For each box that is a child of that element, in that line box, in tree order:
        1. background color of element.
        2. background image of element.
        3. border of element.
        4. For inline elements:
          1. For all the element's in-flow, non-positioned, inline-level children that are in this line box, and all runs of text inside the element that is on this line box, in tree order:
            1. If this is a run of text, then:
              1. any underlining affecting the text of the element, in tree order of the elements applying the underlining (such that the deepest element's underlining, if any, is painted topmost and the root element's underlining, if any, is drawn bottommost).
              2. any overlining affecting the text of the element, in tree order of the elements applying the overlining (such that the deepest element's overlining, if any, is painted topmost and the root element's overlining, if any, is drawn bottommost).
              3. the text.
              4. any line-through affecting the text of the element, in tree order of the elements applying the line-through (such that the deepest element's line-through, if any, is painted topmost and the root element's line-through, if any, is drawn bottommost).
            2. Otherwise, jump to 7.2.1 for that element.

          For inline-block and inline-table elements:

          1. For each one of these, treat the element as if it created a new stacking context, but any descendants which actually create a new stacking context should be considered part of the parent stacking context, not this new one.

          For inline-level replaced elements:

          1. the replaced content, atomically.

        Some of the boxes may have been generated by line splitting or the Unicode bidirectional algorithm.

      2. Optionally, the outline of the element (see 10 below).

    3. Optionally, if the element is block-level, the outline of the element (see 10 below).

  8. All positioned descendants with ‘z-index: auto’ or ‘z-index: 0’, in tree order. For those with ‘z-index: auto’, treat the element as if it created a new stacking context, but any descendants which actually create a new stacking context should be considered part of the parent stacking context, not this new one. For those with ‘z-index: 0’, treat the stacking context generated atomically.

  9. Stacking contexts formed by positioned descendants with z-indices greater than or equal to 1 in z-index order (smallest first) then tree order.

  10. Finally, implementations that do not draw outlines in steps above must draw outlines from this stacking context at this stage. (It is recommended to draw outlines in this step and not in the steps above.)

The background of the root element is only painted once, over the whole canvas.

While the backgrounds of bidirectional inlines are painted in tree order, they are positioned in visual order. Since the positioning of inline backgrounds is unspecified [still the case?], the exact result of these two requirements is UA-defined.

15. Conformance and profiles

16. Acknowledgments

References

Normative references:

[CSS3BG]
Tim Boland; Bert Bos. CSS3 Backgrounds and Borders Module. 16 February 2005. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2005/WD-css3-background-20050216
[CSS3GENCON]
Ian Hickson. CSS3 Generated and Replaced Content Module. 14 May 2003. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2003/WD-css3-content-20030514
[CSS3SYN]
L. David Baron. CSS3 module: Syntax. 13 August 2003. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2003/WD-css3-syntax-20030813
[CSS3TEXT]
Elika J. Etemad. CSS3 Text Module. 27 June 2005. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2005/WD-css3-text-20050627
[CSS3TEXTLAYOUT]
Elika J. Etemad; Paul Nelson. CSS3 Text Layout Module. (forthcoming). W3C Working Draft. (Work in progress.)
[CSS3VAL]
Håkon Wium Lie; Chris Lilley. CSS3 module: Values and Units. 13 July 2001. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2001/WD-css3-values-20010713

Informative references:

[CSS21]
Bert Bos; et al. Cascading Style Sheets, level 2 revision 1. 11 April 2006. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2006/WD-CSS21-20060411
[CSS3CASCADE]
Håkon Wium Lie. CSS3 module: Cascading and inheritance. 19 February 2002. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2002/WD-css3-cascade-20020219
[CSS3GCPM]
Håkon Wium Lie. CSS Generated Content for Paged Media Module. 19 September 2006. W3C Working Draft. (Work in progress) URL: http://www.w3.org/TR/2006/WD-css3-gcpm-20060919
[CSS3LAYOUT]
Bert Bos. CSS3 Advanced Layout Module. 15 December 2005. W3C Working Draft. (Work in progress) URL: http://www.w3.org/TR/2005/WD-css3-layout-20051215/
[CSS3LIST]
Ian Hickson; Tantek Çelik. CSS3 module: Lists. 7 November 2002. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2002/WD-css3-lists-20021107
[CSS3PAGE]
Håkon Wium Lie; Melinda Grant. CSS3 Paged Media Module. 25 February 2004. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2004/CR-css3-page-20040225
[CSS3POS]
Bert Bos. CSS3 Positioning Module. (forthcoming). W3C Working Draft. (Work in progress.)
[CSS3RUBY]
Michel Suignard. CSS3 Ruby Module. 14 May 2003. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2003/CR-css3-ruby-20030514
[CSS3TBL]
Bert Bos; David Hyatt. CSS3 Tables Module. (forthcoming). W3C Working Draft. (Work in progress.)
[MEDIAQ]
Håkon Wium Lie; Tantek Çelik; Daniel Glazman. Media Queries. 8 July 2002. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2002/CR-css3-mediaqueries-20020708

Index

  • alternate, #
  • anonymous box,, #
  • auto
    • value of 'overflow', #
  • background-position, #
  • block, #
  • block-level, #
  • block-progression, #
  • border, #
  • border area, #
  • border-bottom-width, #
  • border edge., #
  • border-left-width, #
  • border-right-width, #
  • border-top-width, #
  • bottom, #
  • canvas, #
  • clear, #
  • collapse, #
  • collapsed through, #
  • compact, #
  • computed value, #
  • containing block, #
  • content area., #
  • content edge., #
  • direction, #
  • display, #
  • element, #
  • float, #
  • flow, #
  • flow root, #
  • height, #
  • hidden, #, #
  • horizontal, #
  • image-scaling, #
  • initial containing block., #
  • inline, #
  • inline-block, #
  • inline-level, #
  • inline-table, #
  • intrinsic, #
  • left, #
  • line box., #
  • list-item, #
  • margin, #
  • margin area, #
  • margin-bottom, #
  • margin edge., #
  • margin-left, #
  • margin-right, #
  • margin-top, #
  • marquee-direction, #
  • marquee-loop, #
  • marquee-speed, #
  • marquee-style, #
  • max-height, #
  • max-width, #
  • min-height, #
  • min-width, #
  • no-content, #
  • no-display, #
  • none, #, #
  • normal flow, #
  • overflow, #
  • overflow-style, #
  • overflow-x, #
  • overflow-y, #
  • padding, #
  • padding area, #
  • padding-bottom, #
  • padding edge., #
  • padding-left, #
  • padding-right, #
  • padding-top, #
  • position, #
  • replaced, #
  • right, #
  • root element., #
  • rotation, #
  • rotation-point, #
  • ruby, #
  • ruby-base, #
  • ruby-base-group, #
  • ruby-text, #
  • ruby-text-group, #
  • run-in, #
  • scroll, #
  • scrolling mechanism, #
  • scroll (marquee-style), #
  • shrink-to-fit, #
  • slide, #
  • static position, #
  • table, #
  • table-caption, #
  • table-cell, #
  • table-column, #
  • table-column-group, #
  • table-footer-group, #
  • table-header-group, #
  • table-row, #
  • table-row-group, #
  • top, #
  • used value., #
  • <angle>, #
  • <bg-position>, #
  • <length>, #
  • <number>, #
  • <page-floats>, #
  • <template>, #
  • vertical., #
  • viewport, #
  • visibility, #
  • visible, #, #
  • width, #
  • z-index, #

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
clear | none | left | right | both | none | block-level elements | no | N/A | visual
display | inline | block | inline-block | list-item | run-in | compact | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | ruby | ruby-base | ruby-text | ruby-base-group | ruby-text-group | <template>| none | inline | all elements | no | N/A | visual (‘none’ applies to all media)
float | left | right | none | <page-floats> | none | all, but see 9.7 | no | N/A | visual
height | <length> | <percentage> | auto | auto | all elements but non-replaced inline elements, table columns, and column groups | no | see prose | visual
margin | [ <length> | <percentage> | auto ]{1,4} | (see individual properties) | see text | no | width* of containing block | visual
margin-top , margin-right, margin-bottom, margin-left | <length> | <percentage> | auto | 0 | see text | no | width* of containing block | visual
marquee-direction | forward | reverse | reverse | same as ‘overflow’ | yes | N/A | visual
marquee-loop | <non-negative-integer> | infinite | 1 | same as ‘overflow’ | no | N/A | visual
marquee-speed | slow | normal | fast | normal | same as ‘overflow’ | no | N/A | visual
marquee-style | scroll | slide | alternate | scroll | same as ‘overflow’ | no | N/A | visual
max-width, max-height | <length> | <percentage> | none | none | all elements but non-replaced inline elements, table rows, and row groups | no | refer to width, resp. height of containing block | visual
min-width, min-height | <length> | <percentage> | inherit | 0 | all elements but non-replaced inline elements, table rows, and row groups | no | refer to width, resp. height of containing block | visual
overflow | [ visible | hidden | scroll | auto | no-display | no-content ]{1,2} | see individual properties | non-replaced block-level elements and non-replaced ‘inline-block’ elements | no | N/A | visual
overflow-style | auto | [scrollbar | panner | move | marquee] [, [scrollbar | panner | move | marquee]]* | auto | same as ‘overflow’ | yes | N/A | visual
overflow-x, overflow-y, | visible | hidden | scroll | auto | no-display | no-content | visible | non-replaced block-level elements and non-replaced ‘inline-block’ elements | no | N/A | visual
padding | [ <length> | <percentage> ]{1,4} | (see individual properties) | all elements | no | width* of containing block | visual
padding-top , padding-right, padding-bottom, padding-left | [ <length> | <percentage> ] | 0 | all elements | no | width* of containing block | visual
rotation | <angle> | 0 | block-level elements, inline-table and inline-block | no | N/A | visual
rotation-point | <bg-position> | 50% 50% | block-level elements | no | Width and height of border box | visual
visibility | visible | hidden | collapse | visible | all elements | yes | N/A | visual
width | <length> | <percentage> | auto | auto | all elements but non-replaced inline elements, table rows, and row groups | no | refer to width of containing block | visual

Properties defined elsewhere:

  • block-progression, direction: [CSS3TEXTLAYOUT]
  • border, border-top-width, border-right-width, border-bottom-width, border-left-width, background-position: [CSS3BG]
  • bottom, top, z-index: [CSS3POS]
  • image-scaling: [CSS3PAGE]
  • position: [CSS3POS] and [CSS3LAYOUT]


CSS3 Basic User Interface Module

W3C Candidate Recommendation 11 May 2004

This version:
http://www.w3.org/TR/2004/CR-css3-ui-20040511
Latest version:
http://www.w3.org/TR/css3-ui
Previous version:
http://www.w3.org/TR/2003/WD-css3-ui-20030703/
Editor:
Tantek Çelik (Microsoft Corporation) <tantekc@microsoft.com>

Copyright © 2004 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.

Abstract

This section is informative.

CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and XML documents on screen, on paper, in speech, etc. It uses various selectors, properties and values to style basic user interface elements in a document. This specification describes those user interface related selectors, properties and values that are proposed for CSS level 3 to style HTML and XML (including XHTML and XForms). It includes and extends user interface related features from the selectors, properties and values of CSS level 2 revision 1 and Selectors specifications.

Status of this document

This section is normative.

This section describes the status of this document at the time of its publication. Other documents may supersede it. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This is a W3C Candidate Recommendation, which means the specification has been widely reviewed and W3C recommends that it be implemented. It will remain Candidate Recommendation at least until 11 November 2004.

Publication as a Candidate Recommendation does not imply endorsement by the W3C Membership. It is inappropriate to cite this document as other than work in progress.

To find the latest version of this specification, please follow the "Latest version" link above, or visit the list of W3C Technical Reports.

A test suite and a report on implementations will be provided before the document becomes a Proposed Recommendation.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this and other specifications in the Style area. When commenting on this document, please put the text "CSS3UI" in the subject, preferably like this: "[CSS3UI] <summary of comment>"

This document is produced by the CSS Working Group (part of the Style Activity, see summary).

Patent disclosures relevant to CSS may be found on the Working Group's public patent disclosure page. The document was developed under the 24 January 2002 CPP as amended by the W3C Patent Policy Transition Procedure.

Candidate Recommendation Exit Criteria

For this specification to exit the CR stage, the following conditions must be met:

  1. There must be at least two interoperable implementations for every feature. For the purposes of this criterion, we define the following terms:

    feature

    A section or subsection of the specification.

    interoperable

    passing the respective test cases in the test suite, or, if the implementation is not a web browser, equivalent tests. Every relevant test in the test suite should have an equivalent test created if such a user agent (UA) is to be used to claim interoperability. In addition if such a UA is to be used to claim interoperability, then there must one or more additional UAs which can also pass those equivalent tests in the same way for the purpose of interoperability. The equivalent tests must be made publicly available for the purposes of peer review.

    implementation

    a user agent which:

    1. implements the feature.
    2. is available (i.e. publicly downloadable or available through some other public point of sale mechanism). This is the "show me" requirement.
    3. is shipping (i.e. development, private or unofficial versions are insufficient).
    4. is not experimental (i.e. is intended for a wide audience and could be used on a daily basis).

  2. A minimum of six months of the CR period must have elapsed. This is to ensure that enough time is given for any remaining major errors to be caught.

  3. The CR period will be extended if implementations are slow to appear.

  4. Features that are at risk (see the below list) will be dropped (thus reducing the list of "all" features mentioned above) if two or more interoperable implementations of those features are not found by the end of the CR period, or if sufficient and adequate tests (by judgment of the Working Group) have not been produced for those features by the end of the CR period.

Features at risk

The Working Group has identified the following features as at risk of being removed from CSS3 Basic User Interface when exiting CR. Implementors are urged to implement these features, if they wish to see these features remain in this specification. All other features are either defined in a normative reference (e.g. CSS 2.1 [CSS21] or Selectors [SELECT]), or dependencies for another specification (e.g. XForms [XFORMS10]) or are believed to have one or more implementations (perhaps experimental), and thus will not be dropped without returning to last call.

  • 'cursor' property values: ew-resize | ns-resize | nesw-resize | nwse-resize
  • 'font' property values: window | document | workspace | desktop | tooltip | dialog | button | push-button | hyperlink | radio-button | checkbox | menu-item | tab | menubar | pull-down-menu | pop-up-menu | list-menu | radio-group | checkbox-group | outline-tree | range | field | combo-box | signature | password
  • 'content' property value: icon
  • 'icon' property
  • 'resize' property

Overview

This section is informative.

This document is one of the "modules" for the upcoming CSS3 specification. It not only describes the user interface related properties and values that already exist in CSS1 [CSS1] and CSS2.1 [CSS21], but introduces new properties and values for CSS3 as well. The Working Group doesn't expect that all implementations of CSS3 will implement all properties or values. Instead, there will probably be a small number of variants of CSS3, so-called "profiles".

This document is the result of the merging of relevant parts of the following Recommendations and Working Drafts, and the addition of some new features.

  • Cascading Style Sheets, level 2, revision 1 [CSS21]
  • User Interface for CSS3 (16 February 2000) [CSSUI]

This specification contains:

  • Pseudo-classes and pseudo-elements to style user interface states and element fragments respectively.
  • Additions to the user interface features in CSS2.1.
  • The ability to style the appearance of various standard form elements in languages such as HTML/XHTML/XForms (and properties to augment or replace some of the remaining stylistic attributes in HTML4/XHTML1).
  • Directional focus navigation properties.
  • A mechanism to allow the styling of elements as icons for accessibility.

Table of contents

  • 1. Introduction
    • 1.1. Purpose
    • 1.2. Scope
  • 2. Conformance
    • 2.1. Definitions
    • 2.2. Classes of products
    • 2.3. Profiles
    • 2.4. Extensions
  • 3. Dependencies on other modules
  • 4. User Interface Selectors
    • 4.1. User interface states: pseudo-classes
      • 4.1.1. :active details
      • 4.1.2. :default
      • 4.1.3. :valid and :invalid
      • 4.1.4. :in-range and :out-of-range
      • 4.1.5. :required and :optional
      • 4.1.6. :read-only and :read-write
    • 4.2. User interface element fragments: pseudo-elements
      • 4.2.1. ::value
      • 4.2.2. ::choices
      • 4.2.3. ::repeat-item
      • 4.2.4. ::repeat-index
  • 5. System Appearance
    • 5.1. Appearance values
    • 5.2. 'appearance' property
    • 5.3. System fonts
  • 6. Element icons
    • 6.1. 'content' property addition
    • 6.2. 'icon' property
  • 7. Box Model addition
    • 7.1. 'box-sizing' property
  • 8. Outline properties
    • 8.1. 'outline' property
    • 8.2. 'outline-width' property
    • 8.3. 'outline-style' property
    • 8.4. 'outline-color' property
    • 8.5. 'outline-offset' property
  • 9. Resizing
    • 9.1. 'resize' property
  • 10. Mouse and Keyboard
    • 10.1. 'cursor' property
    • 10.2. Keyboard control
      • 10.2.1. Sequential navigation order: the 'nav-index' property
      • 10.2.2. Directional focus navigation: the 'nav-up', 'nav-right', 'nav-down', 'nav-left' properties
  • Appendix A. Acknowledgments
  • Appendix B. Bibiliography
  • Appendix C. Changes
  • Appendix D. Default style sheet additions for HTML4/XHTML1
  • Appendix E. Example profiles
  • Appendix F: Test Suite
  • Index
  • Property index

1. Introduction

This section is normative.

CSS3 is a set of modules, divided up and profiled in order to simplify the specification, and to allow implementors the flexibility of supporting the particular modules appropriate for their implementations.

This module describes selectors and CSS properties which enable authors to style user interface related states, element fragments, properties and values.

Section 2.1 of CSS1 [CSS1] and Chapter 18 of CSS2 [CSS2] introduced several user interface related pseudo-classes, properties and values. Section 6.6.4 of Selectors [SELECT] also describes several additional user interface related pseudo-classes (and one pseudo-element).

This Working Draft extends them to provide the ability, through CSS, to style elements based upon additional user interface states, to style fragments of user interface elements, and to alter the dynamic presentation of elements in ways previously only available through specific HTML4/XHTML1 elements and attributes.

1.1. Purpose

The purpose of this specification is to achieve the following objectives:

  • Extend the user interface features in CSS2.1.
  • Provide additional CSS mechanisms to simulate the appearance of various standard form elements.
  • Provide additional CSS mechanisms to augment or replace other dynamic presentation related features in HTML4/XHTML1.
  • Introduce directional navigation properties to assist in the construction of user interfaces which make use of a directional navigation model.
  • Introduce properties and values to specify icon presentations for elements to enhance accessibility.

1.2. Scope

This proposal specifies how to alter the look and feel of various elements, and specifically does not address the meaning behind what a specific look and feel may imply. For example, with the additions in the proposal, an author can make any element look and even feel like a submit button. Yet, that arbitrary element is not afforded any additional meaning, so pushing it does nothing by default, and certainly does not submit a form.

Similarly, the HTML4 <SELECT> element for example, provides a list or menu of choices to the user. The meaning of the HTML4 <SELECT> element is that it allows the user to make a choice, to choose something among several alternatives. This says nothing about its look and feel, and in fact, the "concept" of a HTML4 <SELECT> could be visually implemented as a list-box, a popup-menu, or a group of radio-buttons. Or a group of HTML4 checkboxes (<INPUT type="checkbox">) could be styled to appear as a group of radio-buttons, and yet, since those elements are still semantic checkboxes, they can still be individually checked or unchecked, rather than acquiring any kind of radio-button group semantic where only one can be checked.

Each example of presentation has a different look and feel, but maintains its original meaning, a choice (or choices) among several alternatives. This proposal addresses only the former (look and feel), not the latter (meaning).

Since this proposal serves to simulate the appearance of various user interface and forms elements in HTML4/XHTML, it is perhaps useful to call out what specifically is believed to be outside the scope of CSS, or better suited to document structure rather than style and therefore not addressed by this proposal:

  • Form semantics, including, but not limited to, submission, resetting, naming, what determines a successful or valid form control, and how to process form data.
  • Form contents, including, but not limited to initial value, current value, and form content types. The HTML4 'maxlength' attribute, for example, determines the maximum number of characters the user can enter into an <INPUT type="text"> or <INPUT type="password"> field, and as such is a content constraint rather than a presentational suggestion.
  • Form control dependencies, including, but not limited to, whether only one option from a set of choices may be chosen, or whether multiple options may be chosen.
  • The HTML4/XHTML1 <form> element and its unique attributes ('action', 'method', 'enctype', 'accept', 'accept-charset').

In addition, this document does not attempt to solve all user interface related issues / features that can be found in modern user interfaces. Perhaps future versions may attempt to solve these. For example:

  • Complex or composite controls (e.g. the HTML4 <INPUT type="file"> and the <ISINDEX> elements).
  • The appearance, styling and coloring of scrollbars.
  • Window layering. There is no attempt made to distinguish the appearance of elements in the front-most window versus non-front-most windows. The semantics of window layering must be addressed before it is appropriate to attempt to style such concepts.
  • Palettes and floating windows. Along with the concept of "frontmost" window, windows that float but do not receive focus are also not addressed.
  • Browser window chrome and toolbars.
  • The default styling of the HTML4/XHTML1 <fieldset>, <legend>, <frame> and <frameset> elements.
  • Frame-resizing behavior. The behavior of <frame> and <frameset>, specifically the ability to "share" resizability when elements share a border, perhaps by leveraging the border-collapse property is also not addressed.

2. Conformance

This section is normative.

2.1. Definitions

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 (see [RFC2119]). However, for readability, these words do not typically appear in all uppercase letters in this specification.

Additional key words, e.g. "User agent (UA)", are defined by CSS 2.1 ([CSS21], section 3.1).

2.2. Classes of products

The following classes of products (many of which overlap) should consider implementing this specification:

  • Web browsers
  • User agents that implement one or more of the following types of content: HTML (e.g. [HTML401]), XHTML (e.g. [XHTML10], [XHTML11]), XForms (e.g. [XFORMS10]), SVG (e.g. [SVG10], [SVG11]) or other content languages that contain forms controls or are intended for user interaction
  • User agents that implement one or more levels, modules and or profiles of CSS (e.g. [CSS1], [CSS21])

2.3. Profiles

This specification contains a number of informative profiles. These profiles are not mandatory for conformance.

2.4. Extensions

This specification does not define any explicit extension mechanisms. If an implementation needs to extend the functionality of this specification, it must follow any/all guidelines and requirements of extensions as defined in CSS2.1, e.g. Vendor-specific extensions ([CSS21], section 4.1.2).

3. Dependencies on other modules

This section is normative.

This CSS3 module depends on the following other specifications. Some of these specifications may be in their "Candidate Recommendation" phase. If this module depends on feature or portion of such a specification which ends up being dropped during their "CR" phase(s), then such feature or portion thereof will be presumed to be incorporated into this specification. For example, if the ":indeterminate" selector was dropped from Selectors, then the definition and description of ":indeterminate" would be incorporated into the next draft of this specification.

  • [SELECT]
  • [CSS3COLOR]
  • [CSS21]

The following work is related to the CSS3 Module Basic User Interface Working Draft.

  • [HTML401]
  • [UAAG10]
  • [XML10]
  • [XHTML10]
  • [XHTML11]
  • [XFORMS10]

This specification does not define what is a form element.

4. User Interface Selectors

This section is normative.

4.1. User interface states: pseudo-classes

The Selectors specification defines several user interface selectors ([SELECT], sections 6.6.1 and 6.6.4) which represent user interface states:

  • :hover
  • :active
  • :focus
  • :enabled
  • :disabled
  • :checked
  • :indeterminate

These pseudo-classes as defined by [SELECT] are included in this specification by reference.

CSS 2.1 [CSS21] specifies additional details for some of the selectors mentioned, above and beyond Selectors.

4.1.1. :active details

In addition, on systems with more than one mouse button, :active is clarified to apply only to the primary or primary activation button (typically the "left" mouse button), and any aliases thereof.

Example(s):

restyling a checkbox

Authors may wish to completely redo the styling of a form control, such as a checkbox. This can be achieved using several of the above pseudo-classes and the 'normal' value for the 'appearance' property which is explained later in this specification. In this example, checkboxes with a class of "redone" are styled with specific background images according to their respective user interface states using one or more pseudo-classes.

input[type=checkbox] {
  appearance:checkbox; /* expected from UA defaults */
}

input[type=checkbox].redone {
  appearance:normal;  /* resets various properties */
  display:inline-block;
  width:20px; height:20px;
  background:url(customuncheckedimage.png);
}

input[type=checkbox].redone:active {
  background:url(customuncheckedactiveimage.png);
}

input[type=checkbox].redone:checked {
  background:url(customcheckedimage.png);
}

input[type=checkbox].redone:checked:active {
  background:url(customcheckedactiveimage.png);
}

input[type=checkbox].redone:disabled {
  background:url(customdisableduncheckedimage.png);
}

input[type=checkbox].redone:disabled:checked {
  background:url(customdisabledcheckedimage.png);
}

New user interface state pseudo-classes

In addition to the above-mentioned pseudo-classes, this specification introduces several new pseudo-classes to define additional user interface states.

  • :default
  • :valid
  • :invalid
  • :in-range
  • :out-of-range
  • :required
  • :optional
  • :read-only
  • :read-write

Specifically, these new states (except for :default) are provided as a way to style elements which are in the respective states as defined by XForms [XFORMS10].

4.1.2. :default

The :default selector applies to the one or more UI elements that are the default among a set of similar elements. Typically applies to context menu items, buttons and select lists/menus.

One example is the default submit button among a set of buttons. Another example is the default option from a popup menu. Multiple elements in a select-many group could have multiple :default elements, like a selection of pizza toppings for example.

4.1.3. :valid and :invalid

An element is :valid or :invalid when it is, respectively, valid or invalid with respect to data validity semantics defined by a different specification (e.g. [XFORMS10]). An element which lacks data validity semantics is neither :valid nor :invalid. This is different from an element which otherwise has no constraints. Such an element would always be :valid.

4.1.4. :in-range and :out-of-range

The :in-range and :out-of-range pseudo-classes apply only to elements that have range limitations. An element is :in-range or :out-of-range when the value that the element is bound to is in range or out of range of the presentation (e.g. visual or spoken representation) of the element respectively. An element that lacks data range limits or is not a form control is neither :in-range nor :out-of-range. E.g. a slider element with a value of 11 presented as a slider control that only represents the values from 1-10 is :out-of-range. Another example is a menu element with a value of "E" that happens to be presented as a popup menu that only has choices "A", "B" and "C".

4.1.5. :required and :optional

A form element is :required or :optional if a value for it is, respectively, required or optional before the form it belongs to is submitted. Elements that are not form elements are neither required nor optional.

4.1.6. :read-only and :read-write

An element whose contents are not user-alterable is :read-only. However, elements whose contents are user-alterable (such as text input fields) are considered to be in a :read-write state. In typical documents, most elements are :read-only. However it may be possible (e.g. in the context of an editor) for any element to become :read-write.

4.2. User interface element fragments: pseudo-elements

Selectors ([SELECT], section 7.3) also defines one user interface element fragment selector:

  • ::selection

This pseudo-element is included in this specification as defined by [SELECT] by reference.

In addition to the above-mentioned pseudo-element, this specification introduces four new pseudo-elements to provide access to additional user interface element fragments.

  • ::value
  • ::choices
  • ::repeat-item
  • ::repeat-index

Specifically, these new pseudo-elements are provided as a way to style user interface fragments as defined by XForms [XFORMS10].

4.2.1. ::value

A form element may contain both a label for its data value, and the data value itself. For such elements, the ::value pseudo-element selects the representation of just the data value itself, in order to style its appearance.

Example(s):

fictional markup and illustration

Here is an example which illustrates the ::value of a text input field with fictional markup which is then styled with CSS.

sample XForms fragment with fictional markup:

<input>
  <label>Zip code<label>
  <input::value/>
</input>
sample CSS:

input { border:dashed }
label { border:dotted }
input::value { border:solid }
an (X)HTML+CSS approximation of this example

Spacing (in the form of padding) has been added to the above approximation to separate the borders and make the individual (pseudo-)elements easier to distinguish.

4.2.2. ::choices

Similarly, a form element which represents a list of options may contain both a label for the list, and the list of choices itself. For such elements, the ::choices pseudo-element selects the representation of just the list of choices themselves, in order to style their appearance.

A list of radio buttons can also be selected with the ::choices pseudo-element, and the currently chosen radio button can be selected with the ::value pseudo-element.

4.2.3. ::repeat-item

The ::repeat-item pseudo-element represents a single item from a repeating sequence. It is generated as a parent to all the elements in a single repeating item. Each ::repeat-item is associated with a particular instance data node, and is affected by the model item properties (e.g. 'relevant') found there, as the related style properties will cascade to the child elements.

4.2.4. ::repeat-index

The ::repeat-index pseudo-element represents the current item of a repeating sequence. It takes the place of the ::repeat-item as a parent of all the elements in the index repeating item.

Note. Any style declarations that an author wants to apply to all repeat items, including the index, must be done so by using both ::repeat-item and ::repeat-index selectors. Styles that are only applied to ::repeat-item will not automatically be applied to the respective ::repeat-index.

Example(s):

::repeat-item and ::repeat-index fictional markup

Here is an example that illustrates both ::repeat-item and ::repeat-index, since they are often both available and used at the same time. Assume appropriate namespace declarations were made in a header somewhere preceding the code in the example.

The following markup snippet uses XHTML and XForms:

<html:table xforms:repeat-nodeset="...">
   <html:tr>
      <html:td><xforms:input ref="..."/><xforms:input ref="..."/></html:td>
   </html:tr>
</html:table>

The following style rules are used to style all the repeated items and the current repeated item.

html|tr::repeat-item { outline: medium solid; color:gray }
html|tr::repeat-index { outline: medium dashed; color:black }

The following fictional markup shows the state of the above markup when through user interaction the XForm contains three of the repeated items, where the third item is current.

<html:table xforms:repeat-nodeset="...">
 <html:tr::repeat-item>
  <html:tr>
   <html:td><xforms:input ref="..."/><xforms:input ref="..."/></html:td>
  </html:tr>
 </html:tr::repeat-item>
 <html:tr::repeat-item>
  <html:tr>
   <html:td><xforms:input ref="..."/><xforms:input ref="..."/></html:td>
  </html:tr>
 </html:tr::repeat-item>
 <html:tr::repeat-index>
  <html:tr>
   <html:td><xforms:input ref="..."/><xforms:input ref="..."/></html:td>
  </html:tr>
 </html:tr::repeat-index>
</html:table>

Note. The ::repeat-index pseudo-element takes the place of the ::repeat-item rather than being nested inside as a separate element. Thus just like :link or :visited are mutually exclusive for selecting hyperlinks, only one will exist and apply to a particular repeated item at any point.

Example(s):

UI selectors example from XForms 1.0

The following example from XForms 1.0 ([XFORMS10], section F.3) shows how basic styling can be accomplished on form controls and repeating structures using the new pseudo-classes and XForms elements.

@namespace xforms url(http://www.w3.org/2002/xforms);
/* Display a red background on all invalid form controls */
*:invalid { background-color:red; }
/* Display a red asterisk after all required form controls */
*:required::after { content: "*"; color:red; }
/* Do not render non-relevant form controls */
*:disabled { visibility: hidden; }
/* The following declarations cause form controls and their labels
to align neatly, as if a two-column table were used */
xforms|group { display: table; }
xforms|input { display: table-row; }
xforms|input > xforms|label { display: table-cell; }
xforms|input::value { border: thin black solid; display: table-cell; }
/* Display an alert message when appropriate */
*:valid   > xforms|alert { display: none; }
*:invalid > xforms|alert { display: inline; }
/* Display repeat-items with a dashed border */
*::repeat-item,*::repeat-index { border: dashed; }
/* Display a teal highlight behind the current repeat item */
*::repeat-index { background-color: teal; }

5. System Appearance

This section is normative.

5.1. Appearance values

CSS2 introduced the concept of system colors, which is a set of keywords that allows authors to specify colors in a manner that integrates them into the user's graphic environment. However, color is not the only property for which native form controls have a default.

The properties defined and extended in this section refer to the <appearance> value type, which may take one of the following values which have been derived from the list of CSS2.1 System Colors ([CSS21], section 18.2), the list of HTML4 form controls ([HTML401], section 17), and additional typical platform user interface (UI) controls (e.g. dialog window, icon):

icon
a small picture representing an object, often with a name or label.
window
a viewport, a framed surface used to present objects and content for user viewing and interaction. There are several specific types of windows:
desktop
a window used to represent a system as a whole that often contains other windows.
workspace
a window used to represent a project or application that may contain other windows, typically with a titlebar that shows the name of the project or application.
document
a window used to represent a user document, typically with a titlebar that shows its name. May also be used to represent folders or directories in a file system.
tooltip
a window that is used to temporarily display information or help about an object. Also called "info" in the CSS2 system colors.
dialog
a window used to present a notification or alternatives for the user to choose as part of an action taken by the user. Also called "message-box" in the CSS2 system fonts.
button
a small object usually labeled with text that represents a user choice
push-button
a button that has a border surrounding it, often beveled to appear three dimensional, as if it is raised. Also called "caption" in CSS2 system fonts.
hyperlink
a button that represents a hypertext link, often as simple as normal text that is underlined and perhaps colored differently.
radio-button
a button that displays whether or not it is checked with a small circle next to the button label. There may be a disc inside the circle when the button is checked. An indeterminate (neither checked nor unchecked) state may be indicated with some other graphic in the circle.
checkbox
a button that displays whether or not it is checked with a small box next to the button label. There may be an 'x' or check mark inside the box when the button is checked. An indeterminate (neither checked nor unchecked) state may be indicated with a dash '-' or a square or some other graphic in the box.
menu-item
a choice within a menu, which may also act as a label for a nested (hierarchical) menu.
tab
a button representing the label for a pane in a tabbed interface.
menu
a set of options for the user to choose from, perhaps more than one at a time. There are several specific types of menus.
menubar
a menu of menus, typically arranged linearly, in a horizontal bar.
pull-down-menu
a menu where the name of the menu is displayed and the options remain hidden until the user activates the menu. When the user releases or deactivates the menu, the options are hidden again.
pop-up-menu
a menu where all but the currently selected option remains hidden until the user activates the menu. When the user releases or deactivates the menu, all but the selected option are hidden again.
list-menu
a list of options for the user to choose from, perhaps more than one at a time.
radio-group
a menu where the options are displayed as radio-buttons.
checkbox-group
a menu where the options are displayed as checkboxes.
outline-tree
a menu where the options can be shown or hidden with small widgets, often represented by a small triangle or plus and minus signs.
range
a control that displays the current option, perhaps graphically and allows the user to select other options, perhaps by dragging a slider or turning a knob.
field
an area provided for a user to enter or edit a value, typically using a keyboard. There are several special fields.
combo-box
a field which is accompanied by a menu of preset values that can be used to quickly enter common or typical values.
signature
a field for entering a signature.
password
a field for entering a password. Typically the text is rendered as a set of bullets or boxes to obscure the value.

Conforming user agents must support the five generic appearance values: 'icon', 'window', 'button', 'menu' and 'field'. If a user agent or platform does not support a specific user interface element (e.g. 'dialog'), it may apply the values for the respective generic user interface element (e.g. 'window').

Note. This specification recommends that user agents allow users to override system appearance and font selections with their own choices or proportions, within the user agent. See the User Agent Accessibility Guidelines, specifically Ensure user control of rendering ([UAAG10], section 2 guideline 4).

5.2. 'appearance' property

Name: | appearance
Value: | normal | <appearance> | inherit
Initial: | normal
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual, interactive
Computed value: | specified value

This document introduces the 'appearance' property which can be used to make an element look like a standard user interface element on the platform.

Example(s):

A few 'appearance' values demonstrated using HTML4

'appearance' | HTML4 demonstration
normal | hello
button
push-button
hyperlink | CSS home page
radio-button
checkbox
pop-up-menu
list-menu
radio-group
tea
checkbox-group
pizza toppings
field
password

'appearance' property details

The 'appearance' property is a shorthand for 'appearance', 'color', 'font', and 'cursor'. It sets 'appearance' to the specified value and the other properties to their appropriate system value; 'normal' resets 'appearance' to 'normal' and the others to 'inherit'. The 'appearance' property does not affect the specified or computed values of any other properties.

If 'appearance' is not 'normal', the UA must render the element as if it was the specified user interface (UI) control from the platform. The UA should use the computed values of the 'background-*', 'border-*', 'padding-*', 'outline-*', and 'text-decoration' properties when they do not have their initial values and the computed values of 'color', 'font', and 'cursor' (whatever their values) to influence the rendering where possible. Any values from those properties that cannot be used to influence the rendering of the UI control must not affect the rendering at all.

For example, the UA should not draw a second border around a UI control that already has a border.

If 'background-color' or 'background-image' have non-initial values and the UA is using their values for influencing the rendering of the UI control, then the UA must ensure that the 'color' property is also used to influence the rendering.

Other properties must not affect the handling of 'appearance' and must instead be applied according to normal CSS rules. In particular 'margin', 'display', 'float', 'height', 'width', and 'line-height', are not ignored and affect the element as normal.

This specification does not define the term "platform".

For example, it could be the native graphical rendering engine of the operating system, or it could be a user-agent-specific skin. In addition, which of several toolkits to use could also be decided on an element-by-element basis depending on the values of the 'background-color', 'background-image', 'border-*-style', and 'outline-style' properties, so that the author styles could be honored while still honoring 'appearance' even though the UA is unable to influence the rendering of OS native UI controls.

Note. The exact list of properties set by, influencing, and not affected by 'appearance' given in the lists above may be adjusted based on UA implementor feedback.

Appearance values take into account the user interface state (if any) of the element; thus there is no need for separate values for enabled vs. disabled checkboxes for example.

Example(s):

Influencing the color and background-color of a button

This example demonstrates setting the color and background-color of an element that is set to 'appearance:push-button'.

sample CSS:

input[type=button] {
  appearance:push-button; /* expected from UA defaults */
}

input[type=button].custom {
  color: #393;
  background-color: #9cf;
}
sample (X)HTML fragment:

<input type="button" value="Plain button" />
<input type="button" value="With color" class="custom" />
A graphical browser might render these buttons as follows:

First, a rounded button with black text on a white background, with shades of gray being used near the edges to give the impression of depth. Second, a similar rounded button but with blue text on a light blue background, and with shades of blue used to give the impression of depth.

Your browser on your system:

5.3. System fonts

CSS2 introduced system font keywords as values for the shorthand 'font' property which have the effect of setting all the elemental 'font-*' properties. This specification adds the list of <appearance> values to the set of system fonts to allow styling text the same as such system controls.

Name: | font
System values: | <appearance> | status-bar | message-box | caption | small-caption | inherit
Initial: | see individual properties in CSS 2.1
Applies to: | all elements
Inherited: | yes
Percentages: | N/A for system values
Media: | visual
Computed value: | The computed values for system font keywords are simply the keywords themselves.
icon
The font used to label icons.
window
The font used in the content of a window.
desktop
The font used on the desktop.
workspace
The font used in a workspace window.
document
The font used for the content of a document window.
tooltip
The font used in a tooltip window.
status-bar
The font used in window status bars.
dialog
message-box
The font used in dialog boxes.
button
caption
The font used for buttons (captioned controls etc.).
small-caption
The font used for labeling small controls.
push-button
The specific font used for push-buttons.
hyperlink
The specific font used for hyperlinks.
radio-button
The specific font used for radio-button labels.
checkbox
The font used for checkbox button labels.
menu-item
The font used for menu-item labels.
tab
The font used for tab labels in a tabbed panel interface.
menu
The font used in menus (e.g., dropdown menus and menu lists).
menubar
The specific font used in a menubar.
pull-down-menu
The specific font used in pull-down menus.
pop-up-menu
The specific font used in popup menus.
list-menu
The specific font used in menu lists.
radio-group
The specific font used in radio button groups.
checkbox-group
The specific font used in checkbox button groups.
outline-tree
The specific font used in outline tree views.
range
The specific font used in range controls.
field
The specific font used in form text fields (input or output).
combo-box
The specific font used in a combo-box field.
signature
The specific font used in a signature field.
password
The specific font used in a password field.

6. Element icons

This section is normative.

POWERED BY HeroNote

6.1. 'content' property addition

Name: | content
New Value(s): | icon
Initial: | same as CSS 2.1
Applies to: | same as CSS 2.1
Inherited: | same as CSS 2.1
Percentages: | same as CSS 2.1
Media: | same as CSS 2.1
Computed value: | the keyword 'icon' if specified as such, otherwise same as CSS 2.1
icon
The (pseudo-)element is replaced in its entirety by the resource referenced by its 'icon' property, and treated as a replaced element.

Note. It is expected that the next draft of the CSS3 Generated Content module [CSS3GENCON] will include and superset this functionality.

6.2. 'icon' property

Name: | icon
Value: | auto | <uri> [, <uri>]* | inherit
Initial: | auto
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | all
Computed value: | The computed value for 'auto' is 'auto'. The computed value for the <uri> value is either the fully qualified URI value for the referenced icon that the UA is able to render, or 'auto' if the UA did not find any referenced icons that it could render.
auto
Use a default generic icon provided by the user agent.
<uri>
URIs (see [URI], [RFC1738] and [RFC1808]) provide a way of identifying resources. The <uri> value(s) in this property refer to one or more icons in a comma delimited list. The user agent loads the referenced icons one by one until it finds one that it is able to render. This permits the usage of multiple different icon formats for various platforms, and various media for that matter.

The 'icon' property provides the author the ability to style any arbitrary element with an iconic equivalent. An element's icon is not used/rendered unless the 'content' property is set to the value 'icon' (see above). Documents whose elements have icons assigned to them can be more easily viewed by users who find too much text distracting.

Example(s):

Representing elements with icons

This example uses the above icon features to display icons in place of images and objects.

img,object { content:icon }
  /* note that the CSS3 Generated Content module [CSS3GENCON]
     expands the 'content' property to apply to all elements. */

img { icon:url(imgicon.png); }
  /* provide a custom icon for images */

object { icon:url(objicon.png); }
  /* provide a different custom icon for objects */

7. Box Model addition

This section is normative.

7.1. 'box-sizing' property

Name: | box-sizing
Value: | content-box | border-box | inherit
Initial: | content-box
Applies to: | all elements that accept width or height
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified value
content-box
This is the behavior of width and height as specified by CSS2.1. The specified width and height (and respective min/max properties) apply to the width and height respectively of the content box of the element. The padding and border of the element are laid out and drawn outside the specified width and height.
border-box
The specified width and height (and respective min/max properties) on this element determine the border box of the element. That is, any padding or border specified on the element is laid out and drawn inside this specified width and height. The content width and height are calculated by subtracting the border and padding widths of the respective sides from the specified 'width' and 'height' properties. As the content width and height cannot be negative ([CSS21], section 10.2), this computation is floored at 0.

Note. This is the behavior of width and height as commonly implemented by legacy HTML user agents for replaced elements and input elements.

Example(s):

Using box-sizing to evenly share space

This example uses box-sizing to evenly horizontally split two divs with fixed size borders inside a div container, which would otherwise require additional markup.

sample CSS:

div.container {
    width:38em;
    border:1em solid black;
}

div.split {
    box-sizing:border-box;
    width:50%;
    border:1em silver ridge;
    float:left;
}
sample (X)HTML fragment:

<div class="container">
<div class="split">This div occupies the left half.</div>
<div class="split">This div occupies the right half.</div>
</div>
demonstration of sample CSS and (X)HTML:
This div should occupy the left half.
This div should occupy the right half.
The two divs above should appear side by side, each (including borders) 50% of the content width of their container. If instead they are stacked one on top of the other then your browser does not support 'box-sizing'.

8. Outline properties

This section is normative.

At times, style sheet authors may want to create outlines around visual objects such as buttons, active form fields, image maps, etc., to make them stand out. Outlines differ from borders in the following ways:

  1. Outlines do not take up space.
  2. Outlines may be non-rectangular.

The outline properties control the style of these dynamic outlines.

8.1. 'outline' property

Name: | outline
Value: | [ <'outline-color'> || <'outline-style'> || <'outline-width'> ] | inherit
Initial: | see individual properties
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | undefined for shorthand properties

8.2. 'outline-width' property

Name: | outline-width
Value: | <border-width> | inherit
Initial: | medium
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | <length> value in absolute units (px or physical).

8.3. 'outline-style' property

Name: | outline-style
Value: | auto | <border-style> | inherit
Initial: | none
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified value

8.4. 'outline-color' property

Name: | outline-color
Value: | <color> | invert | inherit
Initial: | invert
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | The computed value for 'invert' is 'invert'. For <color> values, the computed value is as defined for the [CSS3COLOR] 'color' property.

The outline created with the outline properties is drawn "over" a box, i.e., the outline is always on top, and doesn't influence the position or size of the box, or of any other boxes. Therefore, displaying or suppressing outlines does not cause reflow.

Outlines may be non-rectangular. For example, if the element is broken across several lines, the outline should be an outline or minimum set of outlines that encloses all the element's boxes. Each part of the outline should be fully connected rather than open on some sides (as borders on inline elements are when lines are broken). The parts of the outline are not required to be rectangular. The position of the outline may be affected by descendant boxes. User agents should use an algorithm for determining the outline that encloses a region appropriate for conveying the concept of focus to the user.

The 'outline-width' property accepts the same values as 'border-width' ([CSS21], section 8.5.1).

The 'outline-style' property accepts the same values as 'border-style' ([CSS21], section 8.5.3), except that 'hidden' is not a legal outline style. In addition, in CSS3, 'outline-style' accepts the value 'auto'. The 'auto' value permits the user agent to render a custom outline style, typically a style which is either a user interface default for the platform, or perhaps a style that is richer than can be described in detail in CSS, e.g. a rounded edge outline with semi-translucent outer pixels that appears to glow. As such, this specification does not define how the 'outline-color' is incorporated or used (if at all) when rendering 'auto' style outlines. User agents may treat 'auto' as 'solid'.

The 'outline-color' property accepts all colors, as well as the keyword 'invert'. 'Invert' is expected to perform a color inversion on the pixels on the screen. This is a common trick to ensure the focus border is visible, regardless of color background.

Conformant UAs may ignore the 'invert' value on platforms that do not support color inversion of the pixels on the screen. If the UA does not support the 'invert' value then the initial value of the 'outline-color' property is the 'currentColor' [CSS3COLOR] keyword.

The 'outline' property is a shorthand property, and sets all three of 'outline-style', 'outline-width', and 'outline-color'.

Note. The outline is the same on all sides. In contrast to borders, there are no 'outline-top' or 'outline-left' etc. properties.

This specification does not define how multiple overlapping outlines are drawn, or how outlines are drawn for boxes that are partially obscured behind other elements.

Example(s):

Here's an example of drawing a thick outline around a BUTTON element:

button { outline: thick solid }

Graphical user interfaces may use outlines around elements to tell the user which element on the page has the focus. These outlines are in addition to any borders, and switching outlines on and off should not cause the document to reflow. The focus is the subject of user interaction in a document (e.g., for entering text, selecting a button, etc.).

Example(s):

For example, to draw a thick black line around an element when it has the focus, and a thick red line when it is active, the following rules can be used:

:focus  { outline: thick solid black }
:active { outline: thick solid red }

Note. Since the outline does not affect formatting (i.e., no space is left for it in the box model), it may well overlap other elements on the page.

8.5. 'outline-offset' property

By default, the outline is drawn starting just outside the border edge. However, it is possible to offset the outline and draw it beyond the border edge.

Name: | outline-offset
Value: | <length> | inherit
Initial: | 0
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | <length> value in absolute units (px or physical).

If the computed value of 'outline-offset' is anything other than 0, then the outline is outset from the border edge by that amount.

Example(s):

For example, to leave 2 pixels of space between a focus outline and the element that has the focus, or is active, the following rule can be used:

:focus,:active  { outline-offset: 2px }

9. Resizing

This section is normative.

CSS2.1 provides a mechanism for controlling the appearance of a scrolling mechanism (e.g. scrollbars), and this specification adds to that a mechanism for controlling user resizability of elements.

9.1. 'resize' property

The 'resize' property allows the author to specify whether or not an element is resizable by the user, and if so, along which axis/axes.

Name: | resize
Value: | none | both | horizontal | vertical | inherit
Initial: | none
Applies to: | elements with 'overflow' other than visible
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified value.
none
The UA does not present a resizing mechanism on the element, and the user is given no direct manipulation mechanism to resize the element.
both
The UA presents a bidirectional resizing mechanism to allow the user to adjust both the height and the width of the element.
horizontal
The UA presents a unidirectional horizontal resizing mechanism to allow the user to adjust only the width of the element.
vertical
The UA presents a unidirectional vertical resizing mechanism to allow the user to adjust only the height of the element.

Currently it is possible to control the appearance of the scrolling mechanism (if any) on an element using the 'overflow' property (e.g. 'overflow: scroll' vs. 'overflow: hidden' etc.). The purpose of the 'resize' property is to also allow control over the appearance and function of the resizing mechanism (e.g. a resize box or widget) on the element.

Note. The resizing mechanism is NOT the same as the scrolling mechanism. The scrolling mechanism allows the user to determine which portion of the contents of an element is shown. The resizing mechanism allows the user to determine the size of the element.

The 'resize' property applies to elements whose computed 'overflow' value is something other than 'visible'. If 'overflow' is different in a particular axis (i.e. 'overflow-x' vs. 'overflow-y'), then this property applies to the dimension(s) which do not have the value 'visible'.

When an element is resized by the user, the user agent keeps track of a resize factor (which is initially 1.0) for the width and height, which it then applies to the computed width and height as part of determining the used width and height. The element's contents (and surroundings) are reformatted as necessary.

The resize factor introduces a step in width/height calculations and formatting as described in chapter 10 of CSS2.1. Specifically the following step is inserted between steps 1 and 2 of the algorithm in section 10.4 and 10.7 in CSS2.1 [CSS21], where [dimension] is 'width' for 10.4 and 'height' for 10.7.

1b. If the resize [dimension] factor is not 1.0, then the tentative used [dimension] is multiplied by that factor, and the rules above are applied again, but this time using the result of that multiplication as the computed value for '[dimension]'.

With regard to interactivity and the Document Object Model (DOM), the resize factor on an element lasts the lifetime of the element, however, if the 'resize' property itself is altered (e.g. via pseudo-class change or via DOM manipulation), then the resize factor is reset to 1.0.

The precise direction of resizing (i.e. altering the top left of the element or altering the bottom right) may depend on a number of factors including whether the element is absolutely positioned, whether it is positioned using the 'right' and 'bottom' properties, whether the language of the element is right-to-left etc. The precise direction of resizing is left to the UA to properly determine for the platform.

The user agent may restrict the resizing range to something suitable, such as between the original formatted size of the element, and large enough to encompass all the element's contents.

Example(s):

For example, to make iframes scrollable and resizable, the following rule can be used:

iframe,object[type^="text/"],
object[type$="+xml"],object[type="application/xml"]
{
  overflow:auto;
  resize:both;
}

10. Mouse and Keyboard

This section is normative.

10.1. 'cursor' property

Name: | cursor
Value: | [ [<uri> [<x> <y>]?,]* [ auto | default | none | context-menu | help | pointer | progress | wait | cell | crosshair | text | vertical-text | alias | copy | move | no-drop | not-allowed | e-resize | n-resize | ne-resize | nw-resize | s-resize | se-resize | sw-resize | w-resize | ew-resize | ns-resize | nesw-resize | nwse-resize | col-resize | row-resize | all-scroll ] ] | inherit
Initial: | auto
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual, interactive
Computed value: | If there are one or more <uri> values specified, and the UA finds a <uri> that it is able to support (due to format, resource availability etc.), then the computed value is that resolved absolute URI, fully qualified, with optional <x> and <y> coordinates. If no such supported <uri> value is found, or if no <uri> values were specified, then the computed value is the specified keyword value.

Value descriptions

image cursors
<uri>
The user agent retrieves the cursor from the resource designated by the URI. If the user agent cannot handle the first cursor of a list of cursors, it must attempt to handle the second, etc. If the user agent cannot handle any user-defined cursor, it must use the cursor keyword at the end of the list. The optional <x> and <y> coordinates identify the exact position within the image which is the pointer position (i.e., the hotspot).
<x>
<y>
Each is a <number>. The x-coordinate and y-coordinate of the position in the cursor's coordinate system (left/top relative) which represents the precise position that is being pointed to. If the values are unspecified, then the intrinsic hotspot defined inside the image resource itself is used. If both the values are unspecific and the referenced cursor has no defined hotspot, the effect is as if a value of "0 0" were specified.
general purpose cursors
auto
The UA determines the cursor to display based on the current context.
default
The platform-dependent default cursor. Often rendered as an arrow.
none
No cursor is rendered for the element.
links and status cursors
context-menu
A context menu is available for the object under the cursor. Often rendered as an arrow with a small menu-like graphic next to it.
help
Help is available for the object under the cursor. Often rendered as a question mark or a balloon.
pointer
The cursor is a pointer that indicates a link.
progress
A progress indicator. The program is performing some processing, but is different from 'wait' in that the user may still interact with the program. Often rendered as a spinning beach ball, or an arrow with a watch or hourglass.
wait
Indicates that the program is busy and the user should wait. Often rendered as a watch or hourglass.
selection cursors
cell
Indicates that a cell or set of cells may be selected. Often rendered as a thick plus-sign with a dot in the middle.
crosshair
A simple crosshair (e.g., short line segments resembling a "+" sign). Often used to indicate a two dimensional bitmap selection mode.
text
Indicates text that may be selected. Often rendered as a vertical I-beam. User agents may automatically display a horizontal I-beam/cursor (e.g. same as the 'vertical-text' keyword) for vertical text, or for that matter, any angle of I-beam/cursor for text that is rendered at any particular angle.
vertical-text
Indicates vertical-text that may be selected. Often rendered as a horizontal I-beam.
drag and drop cursors
alias
Indicates an alias of/shortcut to something is to be created. Often rendered as an arrow with a small curved arrow next to it.
copy
Indicates something is to be copied. Often rendered as an arrow with a small plus sign next to it.
move
Indicates something is to be moved.
no-drop
Indicates that the dragged item cannot be dropped at the current cursor location. Often rendered as a hand or pointer with a small circle with a line through it.
not-allowed
Indicates that the requested action will not be carried out. Often rendered as a circle with a line through it.
resizing and scrolling cursors
e-resize, n-resize, ne-resize, nw-resize, s-resize, se-resize, sw-resize, w-resize
Indicates that some edge is to be moved. For example, the 'se-resize' cursor is used when the movement starts from the south-east corner of the box.
ew-resize, ns-resize, nesw-resize, nwse-resize
Indicates a bidirectional resize cursor.
col-resize
Indicates that the item/column can be resized horizontally. Often rendered as arrows pointing left and right with a vertical bar separating them.
row-resize
Indicates that the item/row can be resized vertically. Often rendered as arrows pointing up and down with a horizontal bar separating them.
all-scroll
Indicates that the something can be scrolled in any direction. Often rendered as arrows pointing up, down, left, and right with a dot in the middle.

The UA may treat unsupported values as 'auto'. E.g. on platforms that do not have a concept of a 'context-menu' cursor, the UA may render 'default' or whatever is appropriate.

Example: cursor fallback

Here is an example of using several cursor values.

:link,:visited {
    cursor: url(example.svg#linkcursor),
            url(hyper.cur),
            url(hyper.png) 2 3,
            pointer
}

This example sets the cursor on all hyperlinks (whether visited or not) to an external SVG cursor ([SVG10], section 16.8.3). User agents that don't support SVG cursors would simply skip to the next value and attempt to use the "hyper.cur" cursor. If that cursor format was also not supported, the UA could attempt to use the "hyper.png" cursor with the explicit hot spot. Finally if the UA does not support any of those image cursor formats, the UA would skip to the last value and simply render the 'pointer' cursor.

10.2. Keyboard control

10.2.1. Sequential navigation order: the 'nav-index' property

The 'nav-index' property is an input-method-neutral way of specifying the sequential navigation order (also known as "tabbing order").

Name: | nav-index
Value: | auto | <number> | inherit
Initial: | auto
Applies to: | all enabled elements
Inherited: | no
Percentages: | n/a
Media: | interactive
Computed value: | specified value.
auto
The element's sequential navigation order is assigned automatically by the user agent.
<number>
The number (which is non-zero and positive) indicates the sequential navigation order for the element. '1' means first. Elements with the same nav-index value are navigated in document order when that nav-index value is being navigated.

This property is a replacement for the HTML4/XHTML1 attribute 'tabindex' ([HTML401], section 17.11.1). Borrowed and slightly rephrased from the HTML4 Recommendation:

This property specifies the position of the current element in the sequential navigation order for the current document.

The sequential navigation order defines the order in which elements will receive focus when navigated by the user via the keyboard. The sequential navigation order may include elements nested within other elements.

Elements that may receive focus should be navigated by user agents according to the following rules:

  1. Those elements that support the nav-index property and assign a positive value to it are navigated first. Navigation proceeds from the element with the lowest nav-index value to the element with the highest value. Values need not be sequential nor must they begin with any particular value. Elements that have identical nav-index values should be navigated in the order they appear in the character stream.
  2. Those elements that do not support the nav-index property or support it and assign it a value of 'auto' are navigated next. These elements are navigated in the order they appear in the character stream.
  3. Elements that are disabled do not participate in the sequential navigation order.

The actual key sequence that causes sequential navigation or element activation depends on the configuration of the user agent (e.g., the "tab" key is often used for sequential navigation, and the "enter" key is used to activate a selected element).

User agents may also define key sequences to navigate the sequential navigation order in reverse. When the end (or beginning) of the tabbing order is reached, user agents may circle back to the beginning (or end). The key combination "shift-tab" is often used for reverse sequential navigation.

10.2.2. Directional focus navigation: the 'nav-up', 'nav-right', 'nav-down', 'nav-left' properties

Names: | nav-up, nav-right, nav-down, nav-left
Value: | auto | <id> [ current | root | <target-name> ]? | inherit
Initial: | auto
Applies to: | all enabled elements
Inherited: | no
Percentages: | N/A
Media: | interactive
Computed value: | <id> as specified with <target-name> string or keyword.
auto
The user agent automatically determines which element to navigate the focus to in response to directional navigational input.
<id>

The <id> value consists of a '#' character followed by an identifier, similar to a fragment identifier in a URL. It indicates the element to which the focus is navigated to in response to directional navigation input respective to the specific property.

If the <id> refers to the currently focused element, the directional navigation input respective to the nav- property is ignored — there is no need to refocus the same element.

<target-name>
The <target-name> parameter indicates the target frame for the focus navigation. It is a string and it cannot start with the underscore "_" character. If the specified target frame does not exist, the parameter will be treated as the keyword 'current', which means to simply use the frame that the element is in. The keyword 'root' indicates that the user agent should target the full window.

User agents for devices with directional navigation keys respond by navigating the focus according to four respective nav-* directional navigation properties (nav-up, nav-right, nav-down, nav-left). This specification does not define which keys of a device are directional navigational keys.

Note. Typical personal computers have keyboards with four arrow keys. One possible implementation would be to use those four arrow keys for directional navigation. For accessibility and user convenience, user agents should allow configuration of which keys on a keyboard are used for directional navigation.

Example: positioned buttons

Here is an example of buttons positioned in a diamond shape whose navigation order and directional focus navigation is set in such a way to navigate the focus clockwise (or counter-clockwise) around the diamond shape when the user chooses to navigate sequentially or directionally.

button { position:absolute }

button#b1 {
    top:0; left:50%;
    nav-index:1;
    nav-right:#b2; nav-left:#b4;
    nav-down:#b2; nav-up:#b4;
}

button#b2 {
    top:50%; left:100%;
    nav-index:2;
    nav-right:#b3; nav-left:#b1;
    nav-down:#b3; nav-up:#b1;
}

button#b3 {
    top:100%; left:50%;
    nav-index:3;
    nav-right:#b4; nav-left:#b2;
    nav-down:#b4; nav-up:#b2;
}

button#b4 {
    top:50%; left:0;
    nav-index:4;
    nav-right:#b1; nav-left:#b3;
    nav-down:#b1; nav-up:#b3;
}

Whatever markup sequence the buttons may have (which is not specified in this example) is irrelevant in this case because they are positioned, and yet, it is still important to ensure focus navigation behaviors which relate reasonably to the specified layout.

Appendix A. Acknowledgments

This appendix is informative.

Thanks to feedback and contributions from L. David Baron, Bert Bos, Matthew Brealey, Ada Chan, Michael Day, Micah Dubinko, Elika E., Steve Falkenburg, Al Gilman, Ian Hickson, Bjoern Hoehrmann, David Hyatt, Richard Ishida, Sho Kuwamoto, Susan Lesch, Peter Linss, Brad Pettit, Alexander Savenkov, Sebastian Schnitzenbaumer, Etan Wexler, David Woolley and Domel.

Appendix B. Bibiliography

This appendix is normative.

Normative References

[CSS21]
Bert Bos; et al. Cascading Style Sheets, level 2 revision 1. 25 February 2004. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2004/CR-CSS21-20040225
[CSS3COLOR]
Tantek Çelik; Chris Lilley. CSS3 Color Module. 14 May 2003. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2003/CR-css3-color-20030514
[RFC1738]
T. Berners-Lee; L. Masinter; M. McCahill. Uniform Resource Locators (URL). December 1994. Internet RFC 1738. URL: http://www.ietf.org/rfc/rfc1738.txt
[RFC1808]
R. Fielding. Relative Uniform Resource Locators. June 1995. Internet RFC 1808. URL: http://www.ietf.org/rfc/rfc1808.txt
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[SELECT]
Daniel Glazman; et al. Selectors. 13 November 2001. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2001/CR-css3-selectors-20011113
[URI]
T. Berners-Lee; R. Fielding; L. Masinter. Uniform Resource Identifiers (URI): generic syntax. August 1998. Internet RFC 2396. URL: http://www.isi.edu/in-notes/rfc2396.txt

Informative References

[CSS1]
Håkon Wium Lie; Bert Bos. Cascading Style Sheets (CSS1) Level 1 Specification. 17 December 1996. W3C Recommendation. Revised 11 January 1999. URL: http://www.w3.org/TR/1999/REC-CSS1-19990111
[CSS2]
Bert Bos; et al. Cascading Style Sheets, level 2 (CSS2) Specification. 12 May 1998. W3C Recommendation. URL: http://www.w3.org/TR/1998/REC-CSS2-19980512
[CSS3GENCON]
Ian Hickson. CSS3 Generated and Replaced Content Module. 14 May 2003. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2003/WD-css3-content-20030514
[CSSUI]
Tantek Çelik. User Interface for CSS3. 2 August 2002. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2002/WD-css3-userint-20020802
[HTML401]
David Raggett; Arnaud Le Hors; Ian Jacobs. HTML 4.01 Specification. 24 December 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-html401-19991224
[SVG10]
Jon Ferraiolo (ed). Scalable Vector Graphics (SVG) 1.0 Specification. 4 September 2001. W3C Recommendation. URL: http://www.w3.org/TR/2001/REC-SVG-20010904
[SVG11]
Jon Ferraiolo; 藤沢 淳 (FUJISAWA Jun); Dean Jackson (eds). Scalable Vector Graphics (SVG) 1.1 Specification. 14 January 2003. W3C Recommendation. URL: http://www.w3.org/TR/2003/REC-SVG11-20030114
[UAAG10]
Ian Jacobs; Jon Gunderson; Eric Hansen. User Agent Accessibility Guidelines 1.0. 17 December 2002. W3C Recommendation. URL: http://www.w3.org/TR/2002/REC-UAAG10-20021217
[XFORMS10]
Micah Dubinko; et al. XForms 1.0. 14 October 2003. W3C Recommendation. URL: http://www.w3.org/TR/2003/REC-xforms-20031014
[XHTML10]
Steven Pemberton; et al. XHTML™ 1.0 The Extensible HyperText Markup Language (Second Edition). 26 January 2000. W3C Recommendation. Revised on 1 August 2002 URL: http://www.w3.org/TR/2002/REC-xhtml1-20020801
[XHTML11]
Murray Altheim; Shane McCarron. XHTML™ 1.1 - Module-based XHTML. 31 May 2001. W3C Recommendation. URL: http://www.w3.org/TR/2001/REC-xhtml11-20010531
[XML10]
Tim Bray; et al. Extensible Markup Language (XML) 1.0 (Third Edition). 4 February 2004. W3C Recommendation. URL: http://www.w3.org/TR/2004/REC-xml-20040204

Appendix C. Changes

This appendix is informative.

In general this draft contains numerous editorial/grammatical/spelling corrections, and several new informative examples. This appendix describes minor functional changes from the Last Call Working Draft of 3 July 2003 that were made to accommodate last call comments.

  • :active pseudo-class. Clarified that :active only applies to the left mouse button on multibutton mice.
  • :default pseudo-class. Clarified that multiple :default elements are possible, e.g. multiple default options for a select-many.
  • :in-range and :out-of-range pseudo-classes. Added sentence: "An element that lacks data range limits or is not a form control is neither :in-range nor :out-of-range."
  • 'appearance' and 'font' properties. Added user interface elements 'menu-item' and 'tab' in the 'button' group, 'range' to 'menu' group, and, 'signature', 'password' and 'combo-box' to the 'field' group. Better specified 'appearance' property details.
  • Icon functionality (and 'icon' value) moved from 'display' property to 'content' property.
  • 'key-equivalent' property removed.
  • 'cursor' property. Added 'none' keyword.
  • 'resize' property. Changed media group to 'visual' to match 'overflow'. Removed 'auto' value. Changed initial value to 'none' to match current implementation defaults.
  • 'outline-style' property. Added 'auto' keyword.
  • directional navigation properties. Changed <uri> in value description to <id>. Added target keyword 'current' in addition to 'root'.

Appendix D. Default style sheet additions for HTML4/XHTML1

This appendix is informative.

Potential additions to the base style sheet to express HTML4/XHTML1 form controls and a few HTML4/XHTML1 dynamic presentation attributes:

:link,:visited {
 appearance: hyperlink; /* set color, font, background, padding, border, etc.*/
}

:enabled:focus {
 outline: 2px inset;
}

button,
input[type=button],
input[type=reset],
input[type=submit],
input[type=checkbox],
input[type=radio],
textarea,
input,
input[type=text],
input[type=hidden],
input[type=password],
input[type=image]
{
 appearance: button;
 display: inline-block;
 white-space: nowrap;
}

button,
input[type=button],
input[type=reset][value],
input[type=submit][value]
{
/* appearance of HTML4/XHTML1 push buttons */
 appearance: push-button;
}

button
{
/* white space handling of BUTTON tags in particular */
 white-space:normal;
}

input[type=reset]
{
/* default content of HTML4/XHTML1 input type=reset button */
 content: "Reset";
}

input[type=submit]
{
/* default content of HTML4/XHTML1 input type=submit button */
 content: "Submit";
}

input[type=button],
input[type=reset][value],
input[type=submit][value]
{
/* text content/labels of HTML4/XHTML1 "input" buttons */
 content: attr(value);
}

input[type=checkbox]
{
 appearance:checkbox;
}

input[type=radio]
{
 appearance:radio-button;
}

textarea,
input,
input[type=text],
input[type=hidden],
input[type=password]
{
 appearance: field;
}

textarea
{
/* white space handling of TEXTAREA tags in particular */
 white-space:pre-wrap;
}

input[type=password]
{
 appearance: password;
}

input[type=hidden]
{
/* appearance of the HTML4/XHTML1 hidden text field in particular */
 display: none;
}

input[type=image]
{
 display: inline-block;
 content: attr(src,url);
 border: none;
}

select[size]
{
/* HTML4/XHTML1 <select> w/ size more than 1 - appearance of list */
 appearance: list-menu;
 display: inline-block;
 height: attr(size,em);
}

select,select[size=1]
{
/* HTML4/XHTML1 <select> without size, or size=1 - popup-menu */
 appearance: popup-menu;
 display: inline-block;
 height: 1em;
 overflow: hidden;
}

option
{
 appearance:menu-item;
}

select[size]:active
{
/* active HTML4/XHTML <select> w/ size more than 1 - appearance of active list */
 display: inline-block;
}

optgroup,option
{
 display: block;
 white-space: nowrap;
}

optgroup[label],option[label]
{
 content: attr(label);
}

option[selected]::before
{
 display: inline;
 content: check;
}

*[tabindex] { nav-index:attr(tabindex,number) }

/* Though FRAME resizing is not directly addressed by this specification,
   the following rules may provide an approximation of reasonable behavior. */

/*

frame { resize:both }
frame[noresize] { resize:none }

*/

Appendix E. Example profiles

This appendix is informative.

These example profiles are written to roughly reflect the set of functionality that other specifications use/define which has been explicitly defined and/or updated in this specification. These profiles are independent of any other dimensions of variability, e.g. properties that may allow some values to be treated as other values.

This specification recommends that implementations base their support on at least one of the profiles defined below. Thus a CSS2.1 user agent for example, should consider supporting the CSS2.1 profile for CSS3 Basic UI.

CSS1 profile for CSS3 Basic UI

CSS3 Basic User Interface profile
Specification | CSS level 1
Accepts | :active pseudo-class on hyperlinks
Excludes | :hover, :active on non-hyperlinks, :focus, :enabled, :disabled, :checked, :indeterminate pseudo-classes :default, :valid, :invalid, :in-range, :out-of-range, :required, :optional, :read-only, :read-write pseudo-classes ::selection, ::value, ::choices, ::repeat-item, ::repeat-index pseudo-elements 'appearance' property 'font' property keyword additions 'icon' keyword value for 'content' property 'box-sizing' property 'outline', 'outline-width', 'outline-style', 'outline-color', 'outline-offset' properties 'resize' property 'cursor' property 'nav-index', 'nav-up', 'nav-right', 'nav-down', 'nav-left' properties
Extra constraints | none.

CSS2.1 profile for CSS3 Basic UI

CSS3 Basic User Interface profile
Specification | CSS level 2 revision 1
Accepts | :hover, :active, :focus pseudo-classes 'font' property keyword values: 'caption', 'icon', 'menu', 'message-box', 'small-caption', 'status-bar'. 'outline', 'outline-width', 'outline-style', 'outline-color' properties. 'cursor' property
Excludes | :enabled, :disabled, :checked, :indeterminate pseudo-classes :default, :valid, :invalid, :in-range, :out-of-range, :required, :optional, :read-only, :read-write pseudo-classes ::selection, ::value, ::choices, ::repeat-item, ::repeat-index pseudo-elements 'appearance' property 'font' property keyword additions 'icon' keyword value for 'content' property 'box-sizing' property 'outline-offset' property 'resize' property 'cursor' property additions 'nav-index', 'nav-up', 'nav-right', 'nav-down', 'nav-left' properties
Extra constraints | 'cursor' property support omits hotspot for downloaded cursors, and new cursor keyword values. 'outline-style' property does not support 'auto' value.

XForms profile for CSS3 Basic UI

CSS3 Basic User Interface profile
Specification | XForms 1.0
Accepts | :hover, :active, :focus, :enabled, :disabled, :checked, :indeterminate pseudo-classes :default, :valid, :invalid, :in-range, :out-of-range, :required, :optional, :read-only, :read-write pseudo-classes ::value, ::choices, ::repeat-item, ::repeat-index pseudo-elements
Excludes | ::selection pseudo-element 'appearance' property 'outline', 'outline-width', 'outline-style', 'outline-color' properties. 'cursor' property 'font' property keyword additions 'icon' keyword value for 'content' property 'box-sizing' property 'outline-offset' property 'resize' property 'cursor' property additions 'nav-index', 'nav-up', 'nav-right', 'nav-down', 'nav-left' properties
Extra constraints | none.

Full profile for CSS3 Basic UI

CSS3 Basic User Interface profile
Specification | CSS3
Accepts | :hover, :active, :focus, :enabled, :disabled, :checked, :indeterminate pseudo-classes :default, :valid, :invalid, :in-range, :out-of-range, :required, :optional, :read-only, :read-write pseudo-classes ::selection, ::value, ::choices, ::repeat-item, ::repeat-index pseudo-elements 'appearance' property 'outline', 'outline-width', 'outline-style', 'outline-color' properties. 'cursor' property 'font' property keyword additions 'icon' keyword value for 'content' property 'box-sizing' property 'outline-offset' property 'resize' property 'cursor' property additions 'nav-index', 'nav-up', 'nav-right', 'nav-down', 'nav-left' properties
Excludes | none.
Extra constraints | none.

Appendix F: Test Suite

This appendix is informative.

This specification shall refer to a test suite written according to the CSS Test Suite Documentation and following the CSS2.1 Test Case Authoring Guidelines. The test suite shall allow user agents to verify their basic conformance to the specification. This test suite does not pretend to be exhaustive and does not cover all possible combinations of user interface related features. These tests will be made available from the CSS Test Suites home page.

Index

This appendix is informative.

  • appearance, #
  • box-sizing, #
  • content, #
  • cursor, #
  • font, #
  • icon, #
  • invert, #
  • <appearance>, #
  • MAY, #
  • MUST, #
  • MUST NOT, #
  • nav-down, #
  • nav-index, #
  • nav-left, #
  • nav-right, #
  • nav-up, #
  • OPTIONAL, #
  • outline, #
  • outline-color, #
  • outline-offset, #
  • outline-style, #
  • outline-width, #
  • RECOMMENDED, #
  • REQUIRED, #
  • resize, #
  • SHALL, #
  • SHALL NOT, #
  • SHOULD, #
  • SHOULD NOT, #

Property index

This appendix is informative.

Property | Values | Initial | Applies to | Inh. | Percentages | Media
appearance | normal | <appearance> | inherit | normal | all elements | no | N/A | visual, interactive
box-sizing | content-box | border-box | inherit | content-box | all elements that accept width or height | no | N/A | visual
content | icon | same as CSS 2.1 | same as CSS 2.1 | same as CSS 2.1 | same as CSS 2.1 | same as CSS 2.1
cursor | [ [<uri> [<x> <y>]?,]* [ auto | default | none | context-menu | help | pointer | progress | wait | cell | crosshair | text | vertical-text | alias | copy | move | no-drop | not-allowed | e-resize | n-resize | ne-resize | nw-resize | s-resize | se-resize | sw-resize | w-resize | ew-resize | ns-resize | nesw-resize | nwse-resize | col-resize | row-resize | all-scroll ] ] | inherit | auto | all elements | yes | N/A | visual, interactive
font | <appearance> | status-bar | message-box | caption | small-caption | inherit | see individual properties in CSS 2.1 | all elements | yes | N/A for system values | visual
icon | auto | <uri> [, <uri>]* | inherit | auto | all elements | no | N/A | all
nav-index | auto | <number> | inherit | auto | all enabled elements | no | n/a | interactive
nav-up, nav-right, nav-down, nav-left | auto | <id> [ current | root | <target-name> ]? | inherit | auto | all enabled elements | no | N/A | interactive
outline | [ <'outline-color'> || <'outline-style'> || <'outline-width'> ] | inherit | see individual properties | all elements | no | N/A | visual
outline-color | <color> | invert | inherit | invert | all elements | no | N/A | visual
outline-offset | <length> | inherit | 0 | all elements | no | N/A | visual
outline-style | auto | <border-style> | inherit | none | all elements | no | N/A | visual
outline-width | <border-width> | inherit | medium | all elements | no | N/A | visual
resize | none | both | horizontal | vertical | inherit | none | elements with 'overflow' other than visible | no | N/A | visual


CSS3 Color Module

CSS Color Module Level 3

W3C Proposed Recommendation 28 October 2010

This version:
http://www.w3.org/TR/2010/PR-css3-color-20101028
Latest version:
http://www.w3.org/TR/css3-color
Previous version:
http://www.w3.org/TR/2008/WD-css3-color-20080721
Editors:
Tantek Çelik (invited expert, and before at Microsoft Corporation) <tantek@cs.stanford.edu>
Chris Lilley (W3C) <chris@w3.org>
L. David Baron (Mozilla Corporation) <dbaron@dbaron.org>
Additional Authors:
Steven Pemberton (CWI) <steven.pemberton@cwi.nl>
Brad Pettit (Microsoft Corporation) <bradp@microsoft.com>

Copyright © 2010 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and XML documents on screen, on paper, in speech, etc. It uses color-related properties and values to color the text, backgrounds, borders, and other parts of elements in a document. This specification describes color values and properties for foreground color and group opacity. These include properties and values from CSS level 2 and new values.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css3-color” in the subject, preferably like this: “[css3-color] …summary of comment…”

This document was produced by the CSS Working Group (part of the Style Activity).

The W3C Membership and other interested parties are invited to review the document and send comments to www-style@w3.org (with public archive) through 25 November 2010. Advisory Committee Representatives should consult their WBS questionnaires.

A separate implementation report contains a test suite and shows that each test in the test suite was passed by at least two independent implementations.

The list of comments on the most recent Last Call draft explains the changes that were made since that draft. Comments received during the Candidate Recommendation period (for the 14 May 2003 draft) and how they were addressed in this draft can be found in the disposition of comments. Comments received during the Last Call period (for the 14 February 2003 draft) and how they were addressed can be found in the disposition of comments.

The bibliography contains normative references to two W3C specifications that are not Recommendations at the time of publication, although they are believed to be stable. It is currently the intention to keep this specification at Proposed Recommendation level until those specifications are themselves Proposed Recommendations or Recommendations.

A complete list of changes to this document is available.

Publication as a Proposed Recommendation does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Table of Contents

  • 1. Introduction
  • 2. Dependencies
  • 3. Color properties
    • 3.1. Foreground color: the ‘color’ property
    • 3.2. Transparency: the ‘opacity’ property
  • 4. Color units
    • 4.1. Basic color keywords
    • 4.2. Numerical color values
      • 4.2.1. RGB color values
      • 4.2.2. RGBA color values
      • 4.2.3. ‘transparent’ color keyword
      • 4.2.4. HSL color values
        • 4.2.4.1. HSL examples
      • 4.2.5. HSLA color values
    • 4.3. Extended color keywords
    • 4.4. ‘currentColor’ color keyword
    • 4.5. CSS system colors
      • 4.5.1. CSS2 system colors
    • 4.6. Notes on using colors
  • 5. Simple alpha compositing
  • 6. Sample style sheet for (X)HTML
  • 7. Profiles
  • 8. Test suite
  • 9. Call for Implementations of dropped features
  • 10. Acknowledgments
  • 11. Changes
  • 12. References
    • 12.1. Normative
    • 12.2. Informative
  • Index
  • Property index

1. Introduction

CSS beyond level 2 is a set of modules, divided up to allow the specifications to develop incrementally, along with their implementations. This specification is one of those modules.

This module describes CSS properties which allow authors to specify the foreground color and opacity of an element. This module also describes in detail the CSS <color> value type.

It not only defines the color-related properties and values that already exist in CSS1 and CSS2, but also defines new properties and values.

The Working Group doesn't expect that all implementations of CSS3 will implement all properties or values. Instead, there will probably be a small number of variants of CSS3, so-called "profiles". For example, it may be that only the profile for 32-bit color user agents will include all of the proposed color-related properties and values.

The specification is the result of the merging of relevant parts of the following Recommendations and Working Drafts, and the addition of some new features.

  • HTML 4.01 [HTML401]
  • CSS 2.0 [CSS2]
  • SVG 1.0 [SVG10]
  • User Interface for CSS3 (16 February 2000) [CSS3UI]

2. Dependencies

Additional terminology is defined in the Definitions section of [CSS21]. Examples of document source code and fragments are given in XML [XML10] or HTML [HTML401] syntax.

3. Color properties

3.1. Foreground color: the ‘color’ property

Name: color
Value: <color> | inherit
Initial: depends on user agent
Applies to: all elements
Inherited: yes
Percentages: N/A
Media: visual
Computed value:
  • The computed value for basic color keywords, RGB hex values and extended color keywords is the equivalent triplet of numerical RGB values, e.g. six digit hex value or rgb(...) functional value, with an alpha value of 1.
  • The computed value of the keyword ‘transparent’ is the quadruplet of all zero numerical RGBA values, e.g. rgba(0,0,0,0).
  • See the definition of the ‘currentColor’ for how its computed value is determined.
  • For all other values, the computed value is the specified value.

This property describes the foreground color of an element's text content. In addition it is used to provide a potential indirect value (currentColor) for any other properties that accept color values. If the ‘currentColor’ keyword is set on the ‘color’ property itself, it is treated as ‘color: inherit’.

There are different ways to specify lime green:

Example(s):

em { color: lime }               /* color keyword */
em { color: rgb(0,255,0) }       /* RGB range 0-255   */
<color>
Color units are defined in a following section.

3.2. Transparency: the ‘opacity’ property

Opacity can be thought of as a postprocessing operation. Conceptually, after the element (including its descendants) is rendered into an RGBA offscreen image, the opacity setting specifies how to blend the offscreen rendering into the current composite rendering. See simple alpha compositing for details.

Name: | opacity
Value: | <alphavalue> | inherit
Initial: | 1
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | The same as the specified value after clipping the <alphavalue> to the range [0.0,1.0].
<alphavalue>
Syntactically a <number>. The uniform opacity setting to be applied across an entire object. Any values outside the range 0.0 (fully transparent) to 1.0 (fully opaque) will be clamped to this range. If the object is a container element, then the effect is as if the contents of the container element were blended against the current background using a mask where the value of each pixel of the mask is <alphavalue>.

Since an element with opacity less than 1 is composited from a single offscreen image, content outside of it cannot be layered in z-order between pieces of content inside of it. For the same reason, implementations must create a new stacking context for any element with opacity less than 1. If an element with opacity less than 1 is not positioned, implementations must paint the layer it creates, within its parent stacking context, at the same stacking order that would be used if it were a positioned element with ‘z-index: 0’ and ‘opacity: 1’. If an element with opacity less than 1 is positioned, the ‘z-index’ property applies as described in [CSS21], except that ‘auto’ is treated as ‘0’ since a new stacking context is always created. See section 9.9 and Appendix E of [CSS21] for more information on stacking contexts. The rules in this paragraph do not apply to SVG elements, since SVG has its own rendering model ([SVG11], Chapter 3).

4. Color units

A <color> is either a keyword or a numerical specification.

4.1. Basic color keywords

The list of basic color keywords is: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. The color names are case-insensitive.

Color names and sRGB values
Named | Numeric | Color name | Hex rgb | Decimal
 |  | black | #000000 | 0,0,0
 |  | silver | #C0C0C0 | 192,192,192
 |  | gray | #808080 | 128,128,128
 |  | white | #FFFFFF | 255,255,255
 |  | maroon | #800000 | 128,0,0
 |  | red | #FF0000 | 255,0,0
 |  | purple | #800080 | 128,0,128
 |  | fuchsia | #FF00FF | 255,0,255
 |  | green | #008000 | 0,128,0
 |  | lime | #00FF00 | 0,255,0
 |  | olive | #808000 | 128,128,0
 |  | yellow | #FFFF00 | 255,255,0
 |  | navy | #000080 | 0,0,128
 |  | blue | #0000FF | 0,0,255
 |  | teal | #008080 | 0,128,128
 |  | aqua | #00FFFF | 0,255,255

Example(s):

body {color: black; background: white }
h1 { color: maroon }
h2 { color: olive }

4.2. Numerical color values

4.2.1. RGB color values

The RGB color model is used in numerical color specifications. These examples all specify the same color:

Example(s):

em { color: #f00 }              /* #rgb */
em { color: #ff0000 }           /* #rrggbb */
em { color: rgb(255,0,0) }
em { color: rgb(100%, 0%, 0%) }

The format of an RGB value in hexadecimal notation is a ‘#’ immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This ensures that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display.

The format of an RGB value in the functional notation is ‘rgb(’ followed by a comma-separated list of three numerical values (either three integer values or three percentage values) followed by ‘)’. The integer value 255 corresponds to 100%, and to F or FF in the hexadecimal notation: rgb(255,255,255) = rgb(100%,100%,100%) = #FFF. White space characters are allowed around the numerical values.

All RGB colors are specified in the sRGB color space (see [SRGB]). User agents may vary in the fidelity with which they represent these colors, but using sRGB provides an unambiguous and objectively measurable definition of what the color should be, which can be related to international standards (see [COLORIMETRY]).

Values outside the device gamut should be clipped or mapped into the gamut when the gamut is known: the red, green, and blue values must be changed to fall within the range supported by the device. User agents may perform higher quality mapping of colors from one gamut to another. This specification does not define precise clipping behavior. For a typical CRT monitor, whose device gamut is the same as sRGB, the four rules below are equivalent:

Example(s):

em { color: rgb(255,0,0) }       /* integer range 0 - 255 */
em { color: rgb(300,0,0) }       /* clipped to rgb(255,0,0) */
em { color: rgb(255,-10,0) }     /* clipped to rgb(255,0,0) */
em { color: rgb(110%, 0%, 0%) }  /* clipped to rgb(100%,0%,0%) */

Other devices, such as printers, have different gamuts than sRGB; some colors outside the 0..255 sRGB range will be representable (inside the device gamut), while other colors inside the 0..255 sRGB range will be outside the device gamut and will thus be mapped.

4.2.2. RGBA color values

The RGB color model is extended in this specification to include “alpha” to allow specification of the opacity of a color. See simple alpha compositing for details. These examples all specify the same color:

Example(s):

em { color: rgb(255,0,0) }      /* integer range 0 - 255 */
em { color: rgba(255,0,0,1)     /* the same, with explicit opacity of 1 */
em { color: rgb(100%,0%,0%) }   /* float range 0.0% - 100.0% */
em { color: rgba(100%,0%,0%,1) } /* the same, with explicit opacity of 1 */

Unlike RGB values, there is no hexadecimal notation for an RGBA value.

The format of an RGBA value in the functional notation is ‘rgba(’ followed by a comma-separated list of three numerical values (either three integer values or three percentage values), followed by an <alphavalue>, followed by ‘)’. The integer value 255 corresponds to 100%, rgba(255,255,255,0.8) = rgba(100%,100%,100%,0.8). White space characters are allowed around the numerical values.

Implementations must clip the red, green, and blue components of RGBA color values to the device gamut according to the rules for the RGB color value composed of those components.

These examples specify effects that are possible with the rgba() notation:

Example(s):

p { color: rgba(0,0,255,0.5) }        /* semi-transparent solid blue */
p { color: rgba(100%, 50%, 0%, 0.1) } /* very transparent solid orange */

Note. If RGBA values are not supported by a user agent, they should be treated like unrecognized values per the CSS forward compatibility parsing rules ([CSS21], Chapter 4). RGBA values must not be treated as simply an RGB value with the opacity ignored.

4.2.3. ‘transparent’ color keyword

CSS1 introduced the ‘transparent’ value for the background-color property. CSS2 allowed border-color to also accept the ‘transparent’ value. The Open eBook(tm) Publication Structure 1.0.1 [OEB101] extended the ‘color’ property to also accept the ‘transparent’ keyword. CSS3 extends the color value to include the ‘transparent’ keyword to allow its use with all properties that accept a <color> value. This simplifies the definition of those properties in CSS3.

transparent
Fully transparent. This keyword can be considered a shorthand for transparent black, rgba(0,0,0,0), which is its computed value.

4.2.4. HSL color values

CSS3 adds numerical hue-saturation-lightness (HSL) colors as a complement to numerical RGB colors. It has been observed that RGB colors have the following limitations:

  • RGB is hardware-oriented: it reflects the use of CRTs.
  • RGB is non-intuitive. People can learn how to use RGB, but actually by internalizing how to translate hue, saturation and lightness, or something similar, to RGB.

There are several other color schemes possible. Some advantages of HSL are that it is symmetrical to lightness and darkness (which is not the case with HSV for example), and it is trivial to convert HSL to RGB.

HSL colors are encoding as a triple (hue, saturation, lightness). Hue is represented as an angle of the color circle (i.e. the rainbow represented in a circle). This angle is so typically measured in degrees that the unit is implicit in CSS; syntactically, only a <number> is given. By definition red=0=360, and the other colors are spread around the circle, so green=120, blue=240, etc. As an angle, it implicitly wraps around such that -120=240 and 480=120. One way an implementation could normalize such an angle x to the range [0,360) (i.e. zero degrees, inclusive, to 360 degrees, exclusive) is to compute (((x mod 360) + 360) mod 360). Saturation and lightness are represented as percentages. 100% is full saturation, and 0% is a shade of gray. 0% lightness is black, 100% lightness is white, and 50% lightness is “normal”.

POWERED BY HeroNote

So for instance:

Example(s):

* { color: hsl(0, 100%, 50%) }   /* red */
* { color: hsl(120, 100%, 50%) } /* lime */
* { color: hsl(120, 100%, 25%) } /* dark green */
* { color: hsl(120, 100%, 75%) } /* light green */
* { color: hsl(120, 75%, 75%) }  /* pastel green, and so on */

The advantage of HSL over RGB is that it is far more intuitive: you can guess at the colors you want, and then tweak. It is also easier to create sets of matching colors (by keeping the hue the same and varying the lightness/darkness, and saturation)

If saturation is less than 0%, implementations must clip it to 0%. If the resulting value is outside the device gamut, implementations must clip it to the device gamut. This clipping should preserve the hue when possible, but is otherwise undefined. (In other words, the clipping is different from applying the rules for clipping of RGB colors after applying the algorithm below for converting HSL to RGB.)

The algorithm to translate HSL to RGB is simple (here expressed in ABC [ABC] which was used to generate the tables.) In these algorithms, all three values (H, S and L) have been normalized to fractions 0..1:

    HOW TO RETURN hsl.to.rgb(h, s, l):
       SELECT:
      l<=0.5: PUT l*(s+1) IN m2
      ELSE: PUT l+s-l*s IN m2
       PUT l*2-m2 IN m1
       PUT hue.to.rgb(m1, m2, h+1/3) IN r
       PUT hue.to.rgb(m1, m2, h    ) IN g
       PUT hue.to.rgb(m1, m2, h-1/3) IN b
       RETURN (r, g, b)

    HOW TO RETURN hue.to.rgb(m1, m2, h):
       IF h<0: PUT h+1 IN h
       IF h>1: PUT h-1 IN h
       IF h*6<1: RETURN m1+(m2-m1)*h*6
       IF h*2<1: RETURN m2
       IF h*3<2: RETURN m1+(m2-m1)*(2/3-h)*6
       RETURN m1
4.2.4.1. HSL examples

Each table below represents one hue. Twelve equally spaced colors (i.e. at 30° intervals) have been chosen from the color circle: red, yellow, green, cyan, blue, magenta, with all the intermediate colors (the last is the color between magenta and red).

The X axis of each table represents the saturation (100%, 75%, 50%, 25%, 0%).

The Y axis represents the lightness. 50% is “normal”.

 | 0° Reds
 | Saturation
 | 100% | 75% | 50% | 25% | 0%
100 |  |  |  |  |
88 |  |  |  |  |
75 |  |  |  |  |
63 |  |  |  |  |
50 |  |  |  |  |
38 |  |  |  |  |
25 |  |  |  |  |
13 |  |  |  |  |
0 |  |  |  |  |
 | 30° Red-Yellows (=Oranges)
 | Saturation
 | 100% | 75% | 50% | 25% | 0%
100 |  |  |  |  |
88 |  |  |  |  |
75 |  |  |  |  |
63 |  |  |  |  |
50 |  |  |  |  |
38 |  |  |  |  |
25 |  |  |  |  |
13 |  |  |  |  |
0 |  |  |  |  |
 | 60° Yellows
 | Saturation
 | 100% | 75% | 50% | 25% | 0%
100 |  |  |  |  |
88 |  |  |  |  |
75 |  |  |  |  |
63 |  |  |  |  |
50 |  |  |  |  |
38 |  |  |  |  |
25 |  |  |  |  |
13 |  |  |  |  |
0 |  |  |  |  |
 | 90° Yellow-Greens
 | Saturation
 | 100% | 75% | 50% | 25% | 0%
100 |  |  |  |  |
88 |  |  |  |  |
75 |  |  |  |  |
63 |  |  |  |  |
50 |  |  |  |  |
38 |  |  |  |  |
25 |  |  |  |  |
13 |  |  |  |  |
0 |  |  |  |  |
 | 120° Greens
 | Saturation
 | 100% | 75% | 50% | 25% | 0%
100 |  |  |  |  |
88 |  |  |  |  |
75 |  |  |  |  |
63 |  |  |  |  |
50 |  |  |  |  |
38 |  |  |  |  |
25 |  |  |  |  |
13 |  |  |  |  |
0 |  |  |  |  |
 | 150° Green-Cyans
 | Saturation
 | 100% | 75% | 50% | 25% | 0%
100 |  |  |  |  |
88 |  |  |  |  |
75 |  |  |  |  |
63 |  |  |  |  |
50 |  |  |  |  |
38 |  |  |  |  |
25 |  |  |  |  |
13 |  |  |  |  |
0 |  |  |  |  |
 | 180° Cyans
 | Saturation
 | 100% | 75% | 50% | 25% | 0%
100 |  |  |  |  |
88 |  |  |  |  |
75 |  |  |  |  |
63 |  |  |  |  |
50 |  |  |  |  |
38 |  |  |  |  |
25 |  |  |  |  |
13 |  |  |  |  |
0 |  |  |  |  |
 | 210° Cyan-Blues
 | Saturation
 | 100% | 75% | 50% | 25% | 0%
100 |  |  |  |  |
88 |  |  |  |  |
75 |  |  |  |  |
63 |  |  |  |  |
50 |  |  |  |  |
38 |  |  |  |  |
25 |  |  |  |  |
13 |  |  |  |  |
0 |  |  |  |  |
 | 240° Blues
 | Saturation
 | 100% | 75% | 50% | 25% | 0%
100 |  |  |  |  |
88 |  |  |  |  |
75 |  |  |  |  |
63 |  |  |  |  |
50 |  |  |  |  |
38 |  |  |  |  |
25 |  |  |  |  |
13 |  |  |  |  |
0 |  |  |  |  |
 | 270° Blue-Magentas
 | Saturation
 | 100% | 75% | 50% | 25% | 0%
100 |  |  |  |  |
88 |  |  |  |  |
75 |  |  |  |  |
63 |  |  |  |  |
50 |  |  |  |  |
38 |  |  |  |  |
25 |  |  |  |  |
13 |  |  |  |  |
0 |  |  |  |  |
 | 300° Magentas
 | Saturation
 | 100% | 75% | 50% | 25% | 0%
100 |  |  |  |  |
88 |  |  |  |  |
75 |  |  |  |  |
63 |  |  |  |  |
50 |  |  |  |  |
38 |  |  |  |  |
25 |  |  |  |  |
13 |  |  |  |  |
0 |  |  |  |  |
 | 330° Magenta-Reds
 | Saturation
 | 100% | 75% | 50% | 25% | 0%
100 |  |  |  |  |
88 |  |  |  |  |
75 |  |  |  |  |
63 |  |  |  |  |
50 |  |  |  |  |
38 |  |  |  |  |
25 |  |  |  |  |
13 |  |  |  |  |
0 |  |  |  |  |

4.2.5. HSLA color values

Just as the ‘rgb()’ functional notation has the ‘rgba()’ alpha counterpart, the ‘hsl()’ functional notation has the ‘hsla()’ alpha counterpart. See simple alpha compositing for details. These examples specify the same color:

Example(s):

em { color: hsl(120, 100%, 50%) }     /* green */
em { color: hsla(120, 100%, 50%, 1) } /* the same, with explicit opacity of 1 */

The format of an HSLA color value in the functional notation is ‘hsla(’ followed by the hue in degrees, saturation and lightness as a percentage, and an <alphavalue>, followed by ‘)’. White space characters are allowed around the numerical values.

Implementations must clip the hue, saturation, and lightness components of HSLA color values to the device gamut according to the rules for the HSL color value composed of those components.

These examples specify effects that are possible with the hsla() notation:

Example(s):

p { color: hsla(240, 100%, 50%, 0.5) } /* semi-transparent solid blue */
p { color: hsla(30, 100%, 50%, 0.1) }  /* very transparent solid orange */

4.3. Extended color keywords

The table below provides a list of the X11 colors [X11COLORS] supported by popular browsers with the addition of gray/grey variants from SVG 1.0. The resulting list is precisely the same as the SVG 1.0 color keyword names. This specification extends their definition beyond SVG. The two color swatches on the left illustrate setting the background color of a table cell in two ways: The first column uses the named color value, and the second column uses the respective numeric color value.

Named | Numeric | Color name | Hex rgb | Decimal
 |  | aliceblue | #f0f8ff | 240,248,255
 |  | antiquewhite | #faebd7 | 250,235,215
 |  | aqua | #00ffff | 0,255,255
 |  | aquamarine | #7fffd4 | 127,255,212
 |  | azure | #f0ffff | 240,255,255
 |  | beige | #f5f5dc | 245,245,220
 |  | bisque | #ffe4c4 | 255,228,196
 |  | black | #000000 | 0,0,0
 |  | blanchedalmond | #ffebcd | 255,235,205
 |  | blue | #0000ff | 0,0,255
 |  | blueviolet | #8a2be2 | 138,43,226
 |  | brown | #a52a2a | 165,42,42
 |  | burlywood | #deb887 | 222,184,135
 |  | cadetblue | #5f9ea0 | 95,158,160
 |  | chartreuse | #7fff00 | 127,255,0
 |  | chocolate | #d2691e | 210,105,30
 |  | coral | #ff7f50 | 255,127,80
 |  | cornflowerblue | #6495ed | 100,149,237
 |  | cornsilk | #fff8dc | 255,248,220
 |  | crimson | #dc143c | 220,20,60
 |  | cyan | #00ffff | 0,255,255
 |  | darkblue | #00008b | 0,0,139
 |  | darkcyan | #008b8b | 0,139,139
 |  | darkgoldenrod | #b8860b | 184,134,11
 |  | darkgray | #a9a9a9 | 169,169,169
 |  | darkgreen | #006400 | 0,100,0
 |  | darkgrey | #a9a9a9 | 169,169,169
 |  | darkkhaki | #bdb76b | 189,183,107
 |  | darkmagenta | #8b008b | 139,0,139
 |  | darkolivegreen | #556b2f | 85,107,47
 |  | darkorange | #ff8c00 | 255,140,0
 |  | darkorchid | #9932cc | 153,50,204
 |  | darkred | #8b0000 | 139,0,0
 |  | darksalmon | #e9967a | 233,150,122
 |  | darkseagreen | #8fbc8f | 143,188,143
 |  | darkslateblue | #483d8b | 72,61,139
 |  | darkslategray | #2f4f4f | 47,79,79
 |  | darkslategrey | #2f4f4f | 47,79,79
 |  | darkturquoise | #00ced1 | 0,206,209
 |  | darkviolet | #9400d3 | 148,0,211
 |  | deeppink | #ff1493 | 255,20,147
 |  | deepskyblue | #00bfff | 0,191,255
 |  | dimgray | #696969 | 105,105,105
 |  | dimgrey | #696969 | 105,105,105
 |  | dodgerblue | #1e90ff | 30,144,255
 |  | firebrick | #b22222 | 178,34,34
 |  | floralwhite | #fffaf0 | 255,250,240
 |  | forestgreen | #228b22 | 34,139,34
 |  | fuchsia | #ff00ff | 255,0,255
 |  | gainsboro | #dcdcdc | 220,220,220
 |  | ghostwhite | #f8f8ff | 248,248,255
 |  | gold | #ffd700 | 255,215,0
 |  | goldenrod | #daa520 | 218,165,32
 |  | gray | #808080 | 128,128,128
 |  | green | #008000 | 0,128,0
 |  | greenyellow | #adff2f | 173,255,47
 |  | grey | #808080 | 128,128,128
 |  | honeydew | #f0fff0 | 240,255,240
 |  | hotpink | #ff69b4 | 255,105,180
 |  | indianred | #cd5c5c | 205,92,92
 |  | indigo | #4b0082 | 75,0,130
 |  | ivory | #fffff0 | 255,255,240
 |  | khaki | #f0e68c | 240,230,140
 |  | lavender | #e6e6fa | 230,230,250
 |  | lavenderblush | #fff0f5 | 255,240,245
 |  | lawngreen | #7cfc00 | 124,252,0
 |  | lemonchiffon | #fffacd | 255,250,205
 |  | lightblue | #add8e6 | 173,216,230
 |  | lightcoral | #f08080 | 240,128,128
 |  | lightcyan | #e0ffff | 224,255,255
 |  | lightgoldenrodyellow | #fafad2 | 250,250,210
 |  | lightgray | #d3d3d3 | 211,211,211
 |  | lightgreen | #90ee90 | 144,238,144
 |  | lightgrey | #d3d3d3 | 211,211,211
 |  | lightpink | #ffb6c1 | 255,182,193
 |  | lightsalmon | #ffa07a | 255,160,122
 |  | lightseagreen | #20b2aa | 32,178,170
 |  | lightskyblue | #87cefa | 135,206,250
 |  | lightslategray | #778899 | 119,136,153
 |  | lightslategrey | #778899 | 119,136,153
 |  | lightsteelblue | #b0c4de | 176,196,222
 |  | lightyellow | #ffffe0 | 255,255,224
 |  | lime | #00ff00 | 0,255,0
 |  | limegreen | #32cd32 | 50,205,50
 |  | linen | #faf0e6 | 250,240,230
 |  | magenta | #ff00ff | 255,0,255
 |  | maroon | #800000 | 128,0,0
 |  | mediumaquamarine | #66cdaa | 102,205,170
 |  | mediumblue | #0000cd | 0,0,205
 |  | mediumorchid | #ba55d3 | 186,85,211
 |  | mediumpurple | #9370db | 147,112,219
 |  | mediumseagreen | #3cb371 | 60,179,113
 |  | mediumslateblue | #7b68ee | 123,104,238
 |  | mediumspringgreen | #00fa9a | 0,250,154
 |  | mediumturquoise | #48d1cc | 72,209,204
 |  | mediumvioletred | #c71585 | 199,21,133
 |  | midnightblue | #191970 | 25,25,112
 |  | mintcream | #f5fffa | 245,255,250
 |  | mistyrose | #ffe4e1 | 255,228,225
 |  | moccasin | #ffe4b5 | 255,228,181
 |  | navajowhite | #ffdead | 255,222,173
 |  | navy | #000080 | 0,0,128
 |  | oldlace | #fdf5e6 | 253,245,230
 |  | olive | #808000 | 128,128,0
 |  | olivedrab | #6b8e23 | 107,142,35
 |  | orange | #ffa500 | 255,165,0
 |  | orangered | #ff4500 | 255,69,0
 |  | orchid | #da70d6 | 218,112,214
 |  | palegoldenrod | #eee8aa | 238,232,170
 |  | palegreen | #98fb98 | 152,251,152
 |  | paleturquoise | #afeeee | 175,238,238
 |  | palevioletred | #db7093 | 219,112,147
 |  | papayawhip | #ffefd5 | 255,239,213
 |  | peachpuff | #ffdab9 | 255,218,185
 |  | peru | #cd853f | 205,133,63
 |  | pink | #ffc0cb | 255,192,203
 |  | plum | #dda0dd | 221,160,221
 |  | powderblue | #b0e0e6 | 176,224,230
 |  | purple | #800080 | 128,0,128
 |  | red | #ff0000 | 255,0,0
 |  | rosybrown | #bc8f8f | 188,143,143
 |  | royalblue | #4169e1 | 65,105,225
 |  | saddlebrown | #8b4513 | 139,69,19
 |  | salmon | #fa8072 | 250,128,114
 |  | sandybrown | #f4a460 | 244,164,96
 |  | seagreen | #2e8b57 | 46,139,87
 |  | seashell | #fff5ee | 255,245,238
 |  | sienna | #a0522d | 160,82,45
 |  | silver | #c0c0c0 | 192,192,192
 |  | skyblue | #87ceeb | 135,206,235
 |  | slateblue | #6a5acd | 106,90,205
 |  | slategray | #708090 | 112,128,144
 |  | slategrey | #708090 | 112,128,144
 |  | snow | #fffafa | 255,250,250
 |  | springgreen | #00ff7f | 0,255,127
 |  | steelblue | #4682b4 | 70,130,180
 |  | tan | #d2b48c | 210,180,140
 |  | teal | #008080 | 0,128,128
 |  | thistle | #d8bfd8 | 216,191,216
 |  | tomato | #ff6347 | 255,99,71
 |  | turquoise | #40e0d0 | 64,224,208
 |  | violet | #ee82ee | 238,130,238
 |  | wheat | #f5deb3 | 245,222,179
 |  | white | #ffffff | 255,255,255
 |  | whitesmoke | #f5f5f5 | 245,245,245
 |  | yellow | #ffff00 | 255,255,0
 |  | yellowgreen | #9acd32 | 154,205,50

4.4. ‘currentColor’ color keyword

CSS1 and CSS2 defined the initial value of the ‘border-color’ property to be the value of the ‘color’ property but did not define a corresponding keyword. This omission was recognized by SVG, and thus SVG 1.0 introduced the ‘currentColor’ value for the ‘fill’, ‘stroke’, ‘stop-color’, ‘flood-color’, and ‘lighting-color’ properties. CSS3 extends the color value to include the ‘currentColor’ keyword to allow its use with all properties that accept a <color> value. This simplifies the definition of those properties in CSS3.

currentColor
The value of the ‘color’ property. The computed value of the ‘currentColor’ keyword is the computed value of the ‘color’ property. If the ‘currentColor’ keyword is set on the ‘color’ property itself, it is treated as ‘color: inherit’.

4.5. CSS system colors

4.5.1. CSS2 system colors

Deprecated. In addition to being able to assign color keyword values to text, backgrounds, etc., CSS2 allowed authors to specify colors in a manner that integrated them into the user's graphic environment.

For systems that do not have a corresponding value, the specified value should be mapped to the nearest system color value, or to a default color. Note that some profiles of CSS may not support System Colors at all.

The following lists additional values for color-related CSS values and their general meaning. Any color property can take one of the following names. Although these are case-insensitive, it is recommended that the mixed capitalization shown below be used, to make the names more legible.

ActiveBorder
Active window border.
ActiveCaption
Active window caption.
AppWorkspace
Background color of multiple document interface.
Background
Desktop background.
ButtonFace
The face background color for 3-D elements that appear 3-D due to one layer of surrounding border.
ButtonHighlight
The color of the border facing the light source for 3-D elements that appear 3-D due to one layer of surrounding border.
ButtonShadow
The color of the border away from the light source for 3-D elements that appear 3-D due to one layer of surrounding border.
ButtonText
Text on push buttons.
CaptionText
Text in caption, size box, and scrollbar arrow box.
GrayText
Grayed (disabled) text. This color is set to #000 if the current display driver does not support a solid gray color.
Highlight
Item(s) selected in a control.
HighlightText
Text of item(s) selected in a control.
InactiveBorder
Inactive window border.
InactiveCaption
Inactive window caption.
InactiveCaptionText
Color of text in an inactive caption.
InfoBackground
Background color for tooltip controls.
InfoText
Text color for tooltip controls.
Menu
Menu background.
MenuText
Text in menus.
Scrollbar
Scroll bar gray area.
ThreeDDarkShadow
The color of the darker (generally outer) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.
ThreeDFace
The face background color for 3-D elements that appear 3-D due to two concentric layers of surrounding border.
ThreeDHighlight
The color of the lighter (generally outer) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.
ThreeDLightShadow
The color of the darker (generally inner) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.
ThreeDShadow
The color of the lighter (generally inner) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.
Window
Window background.
WindowFrame
Window frame.
WindowText
Text in windows.

DEPRECATED EXAMPLE(S):

For example, to set the foreground and background colors of a paragraph to the same foreground and background colors of the user's window, write the following:

p { color: WindowText; background-color: Window }

Note. The CSS2 System Color values have been deprecated in favor of the CSS3 UI ‘appearance’ property. If you want to emulate the look of a user interface related element or control, please use the ‘appearance’ property instead of attempting to mimic a user interface element through a combination of system colors.

4.6. Notes on using colors

Although colors can add significant amounts of information to document and make them more readable, please consider the W3C Web Content Accessibility Guidelines [WCAG20] when including color in your documents.

  • 1.4.1 Use of Color: Color is not used as the only visual means of conveying information, indicating an action, prompting a response, or distinguishing a visual element

5. Simple alpha compositing

When drawing, implementations must handle alpha according to the rules in Section 14.2 Simple alpha compositing of [SVG11]. (If the ‘color-interpolation’ or ‘color-rendering’ properties mentioned in that section are not implemented or do not apply, implementations must act as though they have their initial values.)

6. Sample style sheet for (X)HTML

This appendix is informative, not normative. This style sheet could be used by an implementation as part of its default styling of HTML4, XHTML1, XHTML1.1, XHTML Basic, and other XHTML Family documents.

html {
    color: black;
    background: white;
}

/* traditional desktop user agent colors for hyperlinks */
:link    { color: blue; }
:visited { color: purple; }

/* default focus outline */
:focus {
    outline: 1px dotted;  /* or 1px dotted invert */
}

7. Profiles

Each specification using CSS3 Color must define the subset of CSS3 Color features it allows and excludes, and describe the local meaning of all the components of that subset.

Non normative examples:

CSS3 Color profile
Specification | HTML4
Accepts | Basic color keywords RGB six digit hex color values
Excludes | ‘color’ property ‘opacity’ property RGB three digit hex color values and RGB functional notation color value RGBA color values HSL and HSLA color values Extended color keywords ‘currentColor’ color value CSS2 UI Colors ‘transparent’ color value
Extra constraints | none.
CSS3 Color profile
Specification | CSS level 1
Accepts | ‘color’ property Basic color keywords RGB color values
Excludes | ‘opacity’ property RGBA color values HSL and HSLA color values Extended color keywords ‘currentColor’ color value CSS2 UI Colors ‘transparent’ color value
Extra constraints | none.
CSS3 Color profile
Specification | CSS level 2
Accepts | ‘color’ property Basic color keywords RGB color values CSS2 UI Colors ‘transparent’ color value
Excludes | ‘opacity’ property RGBA color values HSL and HSLA color values Extended color keywords ‘currentColor’ color value
Extra constraints | ‘transparent’ color value not valid for ‘color’ property. ‘orange’ color value (part of Extended color keywords) is accepted in CSS level 2 revision 1
CSS3 Color profile
Specification | SVG 1.0 and 1.1
Accepts | ‘color’ property ‘opacity’ property Basic color keywords RGB color values CSS2 UI Colors Extended color keywords ‘currentColor’ color value
Excludes | RGBA color values HSL and HSLA color values ‘transparent’ color value
Extra constraints | ‘currentColor’ color value not valid for ‘color’ property.

8. Test suite

A CSS Color Module Test Suite has been developed, although further tests may be added. This test suite is intended to allow user agents to verify their basic conformance to the specification. This test suite does not pretend to be exhaustive and does not cover all possible numerical color values. These tests are available at http://www.w3.org/Style/CSS/Test/#css3-color.

9. Call for Implementations of dropped features

A number of features that were present in the 14 May 2003 Candidate Recommendation are no longer present in this specification. However, the call for implementations for these features remains, and they may be included in a future level of this specification given sufficient implementations and a test suite to demonstrate interoperability. These features are:

  • ICC Color Profile: the ‘color-profile’ property
  • The ‘rendering-intent’ property
  • The ‘@color-profile’ at-rule
  • ‘flavor’ system color

10. Acknowledgments

Thanks to Brad Pettit both for writing up color-profiles, and for implementing it. Thanks to Steven Pemberton for his write up on HSL colors. Thanks especially to the feedback from Marc Attinasi, Bert Bos, Joe Clark, fantasai, Patrick Garies, Tony Graham, Ian Hickson, Susan Lesch, Alex LeDonne, Cameron McCormack, Krzysztof Maczyński, Chris Moschini, Chris Murphy, Christoph Päper, David Perrell, Jacob Refstrup, Dave Singer, Jonathan Stanley, Andrew Thompson, Russ Weakley, Etan Wexler, David Woolley, Boris Zbarsky, Steve Zilles, the XSL FO subgroup of the XSL working group, and all the rest of the www-style community. And thanks to Chris Lilley for being the resident CSS Color expert.

11. Changes

This document differs from the previous, 21 July 2008, Last Call document. In response to comments received, the old section 3.1.1 Gamma correction which was out of date and misleading, has been dropped. An index was added. SVG color keywords were renamed to Extended color keywords, and HTML4 color keywords renamed to Basic color keywords. The phrase ‘predefined colors’ is no longer used. The references have been updated. The description of the currentColor keyword is improved. A number of spelling and grammatical errors have been removed and there have been some improvements to the markup. Lastly, this changes appendix was added.

For a fuller description of the changes and the reasons they were made, please see the Disposition of Comments.

12. References

12.1. Normative

[COLORIMETRY]
Colorimetry, Third Edition. CIE 15:2004. ISBN 978-3-901906-33-6
[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 8 September 2009. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2009/CR-CSS2-20090908
[SRGB]
Multimedia systems and equipment - Colour measurement and management - Part 2-1: Colour management - Default RGB colour space - sRGB. IEC 61966-2-1 (1999-10) ISBN: 2-8318-4989-6 - ICS codes: 33.160.60, 37.080 - TC 100 - 51 pp. as amended by Amendment A1:2003. URL: http://www.iec.ch/nr1899.htm
[SVG11]
Erik Dahlström; et al. Scalable Vector Graphics (SVG) 1.1 (Second Edition). 22 June 2010. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2010/WD-SVG11-20100622

12.2. Informative

[ABC]
Leo Geurts; Lambert Meertens; Steven Pemberton. The ABC Programmer's Handbook. Prentice-Hall. ISBN: 0-13-000027-2. URL: http://www.cwi.nl/~steven/abc
[CSS2]
Ian Jacobs; et al. Cascading Style Sheets, level 2 (CSS2) Specification. 11 April 2008. W3C Recommendation. URL: http://www.w3.org/TR/2008/REC-CSS2-20080411
[CSS3UI]
Tantek Çelik. CSS3 Basic User Interface Module. 11 May 2004. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2004/CR-css3-ui-20040511
[HTML401]
David Raggett; Ian Jacobs; Arnaud Le Hors. HTML 4.01 Specification. 24 December 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-html401-19991224
[OEB101]
Open eBook(tm) Publication Structure 1.0.1. Open eBook Forum(tm). 02 July 2001. URL: http://www.openebook.org/oebps/oebps1.0.1/download/oeb101-xhtml.htm
[SVG10]
Jon Ferraiolo. Scalable Vector Graphics (SVG) 1.0 Specification. 4 September 2001. W3C Recommendation. URL: http://www.w3.org/TR/2001/REC-SVG-20010904
[WCAG20]
Michael Cooper; et al. Web Content Accessibility Guidelines (WCAG) 2.0. 11 December 2008. W3C Recommendation. URL: http://www.w3.org/TR/2008/REC-WCAG20-20081211
[X11COLORS]
Robert B. Hess. Colors By Name. MSDN Online Web Workshop. 02 November 1996. URL: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwebgen/html/X11_names.asp
[XML10]
C. M. Sperberg-McQueen; et al. Extensible Markup Language (XML) 1.0 (Fifth Edition). 26 November 2008. W3C Recommendation. URL: http://www.w3.org/TR/2008/REC-xml-20081126/

Index

  • ActiveBorder, 4.5.1.
  • ActiveCaption, 4.5.1.
  • aliceblue, 4.3.
  • <alphavalue>, 3.2., 4.2.2., 4.2.5.
  • antiquewhite, 4.3.
  • appearance, 4.5.1.
  • AppWorkspace, 4.5.1.
  • aqua, 4.1., 4.3.
  • aquamarine, 4.3.
  • azure, 4.3.
  • Background, 4.5.1.
  • beige, 4.3.
  • bisque, 4.3.
  • black, 4.1., 4.3.
  • blanchedalmond, 4.3.
  • blue, 4.1., 4.3.
  • blueviolet, 4.3.
  • brown, 4.3.
  • burlywood, 4.3.
  • ButtonFace, 4.5.1.
  • ButtonHighlight, 4.5.1.
  • ButtonShadow, 4.5.1.
  • ButtonText, 4.5.1.
  • cadetblue, 4.3.
  • CaptionText, 4.5.1.
  • chartreuse, 4.3.
  • chocolate, 4.3.
  • color, 3.1.
  • <color>, 3.1., 4.
  • color-interpolation, 5.
  • color-rendering, 5.
  • compositing, 5.
  • coral, 4.3.
  • cornflowerblue, 4.3.
  • cornsilk, 4.3.
  • crimson, 4.3.
  • currentColor, 4.4., 3.1., 3.1., 3.1.
  • cyan, 4.3.
  • darkblue, 4.3.
  • darkcyan, 4.3.
  • darkgoldenrod, 4.3.
  • darkgray, 4.3.
  • darkgreen, 4.3.
  • darkgrey, 4.3.
  • darkkhaki, 4.3.
  • darkmagenta, 4.3.
  • darkolivegreen, 4.3.
  • darkorange, 4.3.
  • darkorchid, 4.3.
  • darkred, 4.3.
  • darksalmon, 4.3.
  • darkseagreen, 4.3.
  • darkslateblue, 4.3.
  • darkslategray, 4.3.
  • darkslategrey, 4.3.
  • darkturquoise, 4.3.
  • darkviolet, 4.3.
  • deeppink, 4.3.
  • deepskyblue, 4.3.
  • dimgray, 4.3.
  • dimgrey, 4.3.
  • dodgerblue, 4.3.
  • firebrick, 4.3.
  • floralwhite, 4.3.
  • forestgreen, 4.3.
  • fuchsia, 4.1., 4.3.
  • gainsboro, 4.3.
  • ghostwhite, 4.3.
  • gold, 4.3.
  • goldenrod, 4.3.
  • gray, 4.1., 4.3.
  • GrayText, 4.5.1.
  • green, 4.1., 4.3.
  • greenyellow, 4.3.
  • grey, 4.3.
  • Highlight, 4.5.1.
  • HighlightText, 4.5.1.
  • honeydew, 4.3.
  • hotpink, 4.3.
  • hsl(), 4.2.4.
  • hsla(), 4.2.5.
  • InactiveBorder, 4.5.1.
  • InactiveCaption, 4.5.1.
  • InactiveCaptionText, 4.5.1.
  • indianred, 4.3.
  • indigo, 4.3.
  • InfoBackground, 4.5.1.
  • InfoText, 4.5.1.
  • ivory, 4.3.
  • khaki, 4.3.
  • lavender, 4.3.
  • lavenderblush, 4.3.
  • lawngreen, 4.3.
  • lemonchiffon, 4.3.
  • lightblue, 4.3.
  • lightcoral, 4.3.
  • lightcyan, 4.3.
  • lightgoldenrodyellow, 4.3.
  • lightgray, 4.3.
  • lightgreen, 4.3.
  • lightgrey, 4.3.
  • lightpink, 4.3.
  • lightsalmon, 4.3.
  • lightseagreen, 4.3.
  • lightskyblue, 4.3.
  • lightslategray, 4.3.
  • lightslategrey, 4.3.
  • lightsteelblue, 4.3.
  • lightyellow, 4.3.
  • lime, 4.1., 4.3.
  • limegreen, 4.3.
  • linen, 4.3.
  • magenta, 4.3.
  • maroon, 4.1., 4.3.
  • mediumaquamarine, 4.3.
  • mediumblue, 4.3.
  • mediumorchid, 4.3.
  • mediumpurple, 4.3.
  • mediumseagreen, 4.3.
  • mediumslateblue, 4.3.
  • mediumspringgreen, 4.3.
  • mediumturquoise, 4.3.
  • mediumvioletred, 4.3.
  • Menu, 4.5.1.
  • MenuText, 4.5.1.
  • midnightblue, 4.3.
  • mintcream, 4.3.
  • mistyrose, 4.3.
  • moccasin, 4.3.
  • navajowhite, 4.3.
  • navy, 4.1., 4.3.
  • oldlace, 4.3.
  • olive, 4.1., 4.3.
  • olivedrab, 4.3.
  • opacity, 3.2.
  • orange, 4.3.
  • orangered, 4.3.
  • orchid, 4.3.
  • palegoldenrod, 4.3.
  • palegreen, 4.3.
  • paleturquoise, 4.3.
  • palevioletred, 4.3.
  • papayawhip, 4.3.
  • peachpuff, 4.3.
  • peru, 4.3.
  • pink, 4.3.
  • plum, 4.3.
  • powderblue, 4.3.
  • purple, 4.1., 4.3.
  • red, 4.1., 4.3.
  • #rgb, 4.2.1.
  • rgb(), 4.2.1.
  • rgba(), 4.2.2.
  • rosybrown, 4.3.
  • royalblue, 4.3.
  • #rrggbb, 4.2.1.
  • saddlebrown, 4.3.
  • salmon, 4.3.
  • sandybrown, 4.3.
  • Scrollbar, 4.5.1.
  • seagreen, 4.3.
  • seashell, 4.3.
  • sienna, 4.3.
  • silver, 4.1., 4.3.
  • skyblue, 4.3.
  • slateblue, 4.3.
  • slategray, 4.3.
  • slategrey, 4.3.
  • snow, 4.3.
  • springgreen, 4.3.
  • sRGB, 4.2.1., 4.1.
  • steelblue, 4.3.
  • system colors, 4.5.1.
  • tan, 4.3.
  • teal, 4.1., 4.3.
  • thistle, 4.3.
  • ThreeDDarkShadow, 4.5.1.
  • ThreeDFace, 4.5.1.
  • ThreeDHighlight, 4.5.1.
  • ThreeDLightShadow, 4.5.1.
  • ThreeDShadow, 4.5.1.
  • tomato, 4.3.
  • transparent, 4.2.3., 3.1.
  • turquoise, 4.3.
  • violet, 4.3.
  • wheat, 4.3.
  • white, 4.1., 4.3.
  • whitesmoke, 4.3.
  • Window, 4.5.1.
  • WindowFrame, 4.5.1.
  • WindowText, 4.5.1.
  • yellow, 4.1., 4.3.
  • yellowgreen, 4.3.

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
color | <color> | inherit | depends on user agent | all elements | yes | N/A | visual
opacity | <alphavalue> | inherit | 1 | all elements | no | N/A | visual


CSS3 Flexible Box Layout Module

Flexible Box Layout Module

W3C Working Draft, 23 July 2009

This version:
http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/
Latest version:
http://www.w3.org/TR/css3-flexbox/
Editors:
L. David Baron, Mozilla Corporation, dbaron@dbaron.org
Authors and former editors:
Neil Deakin, Mozilla Corporation, enndeakin@gmail.com
Ian Hickson, formerly of Opera Software, ian@hixie.ch
David Hyatt, Apple, hyatt@apple.com

Copyright © 2009 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

The draft describes a CSS box model optimized for interface design. It provides an additional layout system alongside the ones already in CSS. [CSS21] In this new box model, the children of a box are laid out either horizontally or vertically, and unused space can be assigned to a particular child or distributed among the children by assignment of “flex” to the children that should expand. Nesting of these boxes (horizontal inside vertical, or vertical inside horizontal) can be used to build layouts in two dimensions. This model is based on the box model in the XUL user-interface language used for the user interface of many Mozilla-based applications (such as Firefox).

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css3-flexbox” in the subject, preferably like this: “[css3-flexbox] …summary of comment…”

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This is the first public working draft in the “css3-flexbox” series.

Table of contents

  • 1 Overview
  • 2 Orientation
  • 3 Display order
  • 4 Alignment
  • 5 Flexibility
  • 6 Packing along the box axis
  • 7 Multiple Lines
    • 7.1 Multiple Lines and alignment
  • 8 Relationship to Inlines and blocks
  • Acknowledgments
  • References
    • Normative references
  • Index
  • Property index

1 Overview

Flexible boxes lay out their children using a constraint-based system that supports both relative flexible sizing and intrinsic sizing. Elements within a box may be intrinsically sized yet have their size increased if additional space is available in the container or have their size reduced if less space is available. In addition, the position and order of elements within a box may be modified.

In CSS, flexible boxes (often referred to only as boxes in this specification) may be created by setting the ‘display’ property. A block-level box can be specified with a value of ‘box’ and an inline box can be specified using a value of inline-box.

A block-level box placed inside a block level element is positioned and sized as if it were any other block. An inline-level box placed inside another element is positioned and sized like an inline-block.

Inline children of a flexible box are wrapped in anonymous blocks. All other children are block-level. Elements within boxes are sized intrinsically. This means that the size is determined by the size needed for its content, or, in the case of replaced elements, the size of the replaced element. The intrinsic size of non-replaced elements may be affected by widths and heights specified on the descendants. When determining the intrinsic size of an element, the calculation is done without adding any line breaks, except those necessary (e.g. for content with a white-space of ‘pre’).

Children of boxes may specify their width and height using the ‘width’ and ‘height’ properties. The width and height of replaced elements is computed as with replaced elements in inline contexts. Otherwise, if the width is set to ‘auto’, then the used value is the intrinsic size, which may be calculated using a shrink-to-fit algorithm, as with inline-block elements, i.e., it will be given the minimum amount of space required to lay out the element without unnecessary line breaks. Similarly, if the height is set to ‘auto’, then the used value in a similar manner.

An unnested box placed inside an enclosing block will obey all the usual sizing rules of the block. For example, setting the width of an unnested box to 100% ensures that the box is the maximum width permitted by the enclosing block (ignoring any margins, border and padding on that box).

The difference between boxes and blocks is in how the children of the element are laid out. Children of boxes are all block-level (inline-level contents get wrapped in anonymous blocks, as described in the section on inlines and blocks). These blocks then get stacked in the direction specified by the ‘box-orient’ and ‘box-direction’ properties, and order specified by the ‘box-ordinal-group’ property. They are aligned within the box according to the ‘box-align’ property. The boxes may then flex or be distributed as specified by the ‘box-flex’, ‘box-flex-group’, ‘box-pack’ and ‘box-lines’ properties.

The ‘float’ and ‘clear’ properties do not apply to children of box elements, so the used value for these properties is ‘none’. These properties do apply to the box itself if it is not a child of another box.

For example:

   <p style="width: 400px;">
     <button style="width: 200px;">Child 1</button>
     <button style="width: 100px;">Child 2</button>
   </p>

In this example, the first button is 200 pixels wide and the second button is 100 pixels wide. As the box is 400 pixels wide, there is extra space left over which is placed after the two buttons but inside the box. The placement of this extra space may be modified using the various box properties described in the next sections. Neither the height of the buttons nor the height of the box are specified, so the height is computed intrinsically from the content. In this case, the buttons will be the height needed to display the label and button border, and the box will also be this height plus any margins around the buttons.

Elements within a box may use the ‘overflow’ property to control whether a scrolling mechanism appears when the children of a box overflow. A scrolling mechanism may be displayed when flexible elements are reduced below their minimum intrinsic size when the overflow property is set to auto or scroll. If overflow is hidden, the element will be clipped instead. Note that the initial value is visible, which is typically not the preferred effect in user interfaces.

2 Orientation

Name: | box-orient
Value: | horizontal | vertical | inline-axis | block-axis | inherit
Initial: | inline-axis
Applies to: | box elements
Inherited: | no
Percentages: | no
Media: | visual
Computed value: | specified value

A box may lay out its children either horizontally or vertically.

horizontal
The box displays its children from left to right in a horizontal line.
vertical
The box displays its children from stacked from top to bottom vertically.
inline-axis
The box displays its children along the inline axis.
block-axis
The box displays its children along the block axis.

The inline and block axes are the writing-mode dependent keywords which, in English, map to horizontal and vertical respectively.

3 Display order

Children within a horizontally oriented box are, by default, displayed from left to right in the same order as they appear in the source document. Children within a vertically oriented box are displayed top to bottom in the same order. The box-direction and box-ordinal-group properties may be used to change this ordering.

Name: | box-direction
Value: | normal | reverse | inherit
Initial: | normal
Applies to: | box elements
Inherited: | no
Percentages: | no
Media: | visual
Computed value: | specified value

The ‘box-direction’ property specifies the direction in which children of a box are displayed.

normal
A box with a computed value of horizontal for box-orient displays its children from left to right. A box with a computed value of vertical displays its children from top to bottom.
reverse
A box with a computed value of horizontal for box-orient displays its children from right to left. A box with a computed value of vertical displays its children from bottom to top.

If the computed value for the box's ‘direction’ property is ‘normal’, a child's left edge is placed next to the right edge of the previous child, or the left edge of the box for the first child. If the computed value for the box's ‘direction’ property is ‘reverse’, a child's right edge is placed next to the left edge of the previous child, or the right edge of the box for the first child.

When the computed value for the overflow property is ‘visible’, ‘scroll’ or ‘auto’, the content may overflow the container. If the computed value for direction is normal, the content will overflow over the right or bottom side. If the computed value for direction is reverse, the content will overflow over the left or top side.

Name: | box-ordinal-group
Value: | <integer>
Initial: | 1
Applies to: | children of box elements
Inherited: | no
Percentages: | no
Media: | visual
Computed value: | specified value

The children of a box element may be assigned to ordinal groups using the ‘box-ordinal-group’ property. This property is a natural number value with an initial value is 1.

Ordinal groups can be used in conjunction with the ‘box-direction’ property to control the order in which the direct children of a box appear. When the computed box-direction is normal, a box will display its elements starting from the lowest numbered ordinal group and ensure that those elements appear to the left (for horizontal boxes) or at the top (for vertical boxes) of the container. Elements with the same ordinal group are flowed in the order they appear in the source document tree. In the reverse direction, the ordinal groups are examined in the same order, except the elements appear reversed.

This example shows how ordinal groups might be used.

    #div1 { display: box; }
    #span1 { box-ordinal-group: 2; }
    #span3 { box-ordinal-group: 2; }
    #span4 { box-ordinal-group: 1; }

    <div id="div1">
      <span id="span1" >Sentence One</span>
      <span id="span2" >Sentence Two</span>
      <span id="span3" >Sentence Three</span>
      <span id="span4" >Sentence Four</span>
    </div>

The first ordinal group, 1, contains span2 and span4. As span2 does not specify an ordinal group, it will default to 1. The elements will be displayed in document order, so span2 will be displayed before span4. The second ordinal group, 2, contains the remaining two spans. The resulting display order will be:

    span2 span4 span1 span3

Elements within a box can use the ‘visibility’ property to render themselves invisible. Boxes behave like tables in that the value collapsed can be used to specify that an element within a box should not take up any space at all. The computed width and height of a collapsed element are both 0, and the element is not considered when calculating flexibility. Other non-collapsed flexible elements may expand as needed to fill in any space left open by a collapsed element.

4 Alignment

Name: | box-align
Value: | start | end | center | baseline | stretch
Initial: | stretch
Applies to: | box elements
Inherited: | no
Percentages: | no
Media: | visual
Computed value: | specified value

When the size of the containing box is larger than the size of a child, extra space will be available. The ‘box-align’ property specifies how a box's children are placed and aligned along the direction perpendicular to the box orientation, and where the extra space, if any, is positioned. For horizontal orientation, it specifies how the children are positioned vertically. For vertical orientation, it specifies how the children are positioned horizontally.

The amount of extra space may be different for each child. For example, if the containing box has a height of 200 pixels, and it contains two children at 100 and 150 pixels respectively, there will be 100 pixels of extra space for the first child and 50 pixels of space for the second child.

The following values are valid for the box-align property, but see the text afterward for more specifics as to how children are positioned.

start
For normal direction boxes, the top edge of each child is placed along the top of the box. Extra space is placed below the element. For reverse direction boxes, the bottom edge of each child is placed along the bottom of the box. Extra space is placed above the element.
end
For normal direction boxes, the bottom edge of each child is placed along the bottom of the box. Extra space is placed above the element. For reverse direction boxes, the top edge of each child is placed along the top of the box. Extra space is placed below the element.
center
Any extra space is divided evenly, with half placed above the child and the other half placed after the child.
baseline
If this box orientation is inline-axis or horizontal, all children are placed with their baselines aligned, and extra space placed before or after as necessary. For block flows, the baseline of the first non-empty line box located within the element is used. For tables, the baseline of the first cell is used. The children, once aligned on their baselines, should then be placed into the box so that the child with the earliest extent margin has its top margin edge (or bottom margin edge for reverse direction boxes) flush with the top (or bottom) edge of the box's content area. If the box does not have an ‘auto’ height, overflow will always be on the bottom (or top for reverse direction boxes) edge. If the box orientation is block-axis or vertical, then baseline is interpreted as center.
stretch
The height of each child is adjusted to that of the containing block. However, note the text below.

The following rules should be applied when determining the size of children inside boxes in the dimension opposite to the orientation of the box. Exceptions to these rules are noted under each of the possible values of ‘box-align’ below.

All normal flow children of boxes will attempt to satisfy the following sizing equation when placed inside vertical boxes if and only if at least one of the specified values is auto:

‘margin-left’ + ‘border-left-width’ + ‘padding-left’ + ‘width’ + ‘padding-right’ + ‘border-right-width’ + ‘margin-right’ = width of containing box

and a similar equation for height when placed inside horizontal boxes:

‘margin-top’ + ‘border-top-width’ + ‘padding-top’ + ‘height’ + ‘padding-bottom’ + ‘border-bottom-width’ + ‘margin-bottom’ = height of containing box

If all the values in the equation are specified (i.e., if there are no auto values), then the equation above does not apply, and the specified values should be used. If applying the equation results in a negative value for width/height, then that value is set to 0, and those values should be used.

If the value of ‘box-align’ is stretch, then elements obey the sizing rules specified above. This is the default value. If both width/height and one or both margin values are ‘auto’, the ‘auto’ margins are set to 0 and the equation is used to find a value for width/height. Otherwise, if both margins are ‘auto’, then the equation is solved under the additional constraint that the two margins must get the same value. If neither the width/height or either margin is auto, then the extra space is positioned as if box-align was start.

If the value of ‘box-align’ is start, center, baseline, or end, and a value of ‘auto’ is specified for width/height, then the intrinsic size (or shrink to fit size) of the element should be used. If one margin has the value of auto, then the equations above should be used. If both margins have a value of auto then the above equations should be used, with the space being divided evenly between the two margins. These rules are similar to the rules for replaced elements inside blocks.

If the above would cause the width or height to greater than the computed maximum width or height, then the width or height is set to the maximum width or height, and the auto margins increased by the extra amount left over. If both margins are auto, they should both be increased by the same amount. If neither margin is auto, the extra space is placed as necessary depending on the box-align value.

Once the sizes are computed, the margin boxes of the elements should be aligned at the start, center, baseline, or end of the box. For horizontal boxes, this typically means the top, center, baseline or bottom of the box. For vertical boxes, the start and end alignments depend upon the direction. For LTR, the elements would be aligned at the left side of the box for start and the right side for end. For RTL, the elements would be aligned at the right of the box for start and the left side for end.

5 Flexibility

Each element directly within a box may be made either flexible and inflexible. Flexible elements may grow when the containing box has extra space available after the size of all of its children have been computed, and shrink if the size would cause the containing box to overflow, yet the preferred width of the flexible element is larger than its minimum width. Inflexible elements do not change in size, even when there is extra space left over in the box.

The flexibility only affects the size in the axis along the box's orientation. (e.g. the flexibility only affects the width in a horizontal box, and only the height in a vertical box.)

Name: | box-flex
Value: | <number>
Initial: | 0.0
Applies to: | in-flow children of box elements
Inherited: | no
Percentages: | no
Media: | visual
Computed value: | specified value
Name: | box-flex-group
Value: | <integer>
Initial: | 1
Applies to: | in-flow children of box elements
Inherited: | no
Percentages: | no
Media: | visual
Computed value: | specified value

POWERED BY HeroNote

An element is flexible when the box-flex property is specified. The box-flex property is a floating point value representing the flexibility of the element. Its initial value is 0, which indicates that the element is inflexible. Elements that are flexible can shrink or grow as the box shrinks and grows. Whenever there is extra space left over in a box, the flexible elements are expanded to fill that space. All flex is relative. For example, a child with a box-flex of 2 is twice as flexible as a child with a box-flex of 1. A negative value for box-flex is not allowed.

Flexible elements can be assigned to flex groups using the ‘box-flex-group’ property. This property is a natural number value (the first flex group is 1 and higher values are later flex groups). The initial value is 1.

In a horizontally oriented box, the preferred width of each child is computed. If the width of the margin box of each child is equal to the width of the containing block, then there is no extra space available, so the preferred widths are used for each child. If the width of the margin box adds up to a value smaller than the width of the containing block, then extra space is available. This extra space is divided up among the flexible children, as described below. If the width of the margin box adds up to a value larger than the width of the containing block, then the flexible children shrink as much as necessary to prevent overflow.

Flexibility only applies to elements in normal flow. As absolute and fixed positioned elements are not in flow, any flexibility or flexgroup specified on them is ignored. In addition, as the ‘float’ property does not apply to children of flexible boxes, they are considered part of normal flow and flexibility does apply.

When dividing up extra space, first take all elements within the first flex group. Each element within that group should be given extra width based on the ratio of that element's flexibility compared to the flexibility of other elements within the same flex group.

However, if the preferred width of the element plus the extra width allotted to it is larger than the maximum width of the element, then the width is set to that maximum width, and any remaining extra width beyond that is divided up among the other children.

In this example there is 60 pixels of extra space available in the containing box.

    #div1 { display: box; width: 300px; }
    #button1 { box-flex: 1.0; width: 100px; }
    #button2 { box-flex: 2.0; width: 140px; }

    <div id="div1">
      <button id="button1">Hello</button>
      <button id="button2">Goodbye</button>
    </div>

As both child buttons are flexible, the extra space will be divided up between them. The first child button has a flexibility of 1.0 and the second child button has a flexibility of 2.0. The first button will receive 20 pixels of extra width and the second button will receive 40 pixels of extra width, maintaining the same ratio of extra width to flexibility values. This extra width is added to the preferred size of the element.

However, if the second button had a maximum width of 150 pixels, it could only grow by 10 pixels before hitting this maximum size, so the remaining 30 pixels would instead be given to the first element, breaking the flexibility ratio.

More specifically, the percentage of extra space that an element may receive is calculated as follows:

‘box-flex of child’ / ‘total of box-flex values of child and all siblings’

If the width of all flexible children within the group has been increased to their maximum widths, the process repeats for the children within the next flex group, using any space left over from the previous flex group. Once there are no more flex groups, and there is still space remaining, the extra space is divided within the containing box according to the box-pack property.

If the box would overflow after the preferred width of the children have been computed, then width is removed from flexible elements in a manner similar to that used when adding extra space. Each flex group is examined in turn and space is removed according to the ratio of the flexibility of each element. Elements do not shrink below their minimum widths.

If all children have been shrunk to their minimum sizes, then the box overflows, although if the box-lines property is set to multiple, the box may be able to move elements to additional lines to prevent this.

For vertically oriented boxes, the algorithm as described above is similar except using the height instead of the width.

When a child box of a horizontally oriented box contains an inline element, it is likely that shrinking the width of the element due to flexibility may cause the inline element to grow in height, as the text within it may need to wrap to additional lines.

Examples:

    #div1 { display: box; box-orient: vertical; height: 200px }

    <div id="div1">
      <button>Cat</button>
      <button style="box-flex: 1">Piranha</button>
      <button>Antidisestablishmentarianism</button>
    </div>

In the example above, the box is 200 pixels tall and is more than enough room for the three buttons. Because the first and third buttons are inflexible, they remain the same size, which is their intrinsic size. The second button is specified as being flexible, and because it is the only flexible element in the box, it receives all of the extra space.

    <div style="display: box; box-orient: vertical;">
      <button style="box-flex: 1; height: 1000px;">
        Cat
      </button>
    </div>

In this example, if the height of the box is reduced, for instance, because the user resized the containing viewport, the height of the flexible button also shrinks with the box, despite the specification of 1000 pixels as the preferred height. It continues to shrink until the minimum required height for the button is reached, which here will likely be the height needed to display the button's label and border. After that, the button can shrink no further. Elements within a box can therefore have their own notions of minimum and maximum intrinsic sizes. In the above example, the button could not get any smaller than the minimum height required to draw its borders and its text.

    #div1 { display: box; }
    #iframe1 { box-flex: 1; min-width: 100px; max-width: 300px; height: 300px; }

    <div id="div1">
      <iframe id="iframe1" src="http://www.mozilla.org/"/>
    </div>

In this example, the iframe has a minimum width of 100 pixels and a maximum width of 300 pixels. If the containing box is less than 100 pixels wide, the iframe will overflow its containing div. If the containing box is between 100 pixels and 300 pixels inclusive, the width of the iframe would be set to that size, minus any necessary padding, borders and margins. If the width of the containing box is larger than 300 pixels, the extra space will be added inside the div. The extra space is added after the iframe inside the box.

    <p style="display: box;">
      <button style="box-flex: 1; max-width: 50px;">Child 1</button>
      <button style="box-flex: 1; min-width: 50px;">Child 2</button>
    </p>

In this example, the box has been stretched so that it is very wide. The first child has a maximum width of 50 pixels, and it divides the excess space equally with the second child until its maximum width has been reached. After that, since it is not allowed to grow any further, the remaining space all goes to the second child.

6 Packing along the box axis

Name: | box-pack
Value: | start | end | center | justify
Initial: | start
Applies to: | box elements
Inherited: | no
Percentages: | no
Media: | visual
Computed value: | specified value

When all of the elements within a box are inflexible or when all elements have grown to their maximum sizes and can stretch no further, extra space may be left over in the box. The box-pack property may be used to dictate how any additional space along the box-axis should be distributed between elements. The box-pack property does not affect the position of elements in the opposite direction. That is, box-pack affects only the horizontal position in horizontally oriented boxes and only the vertical position in vertically oriented boxes.

start
For normal direction boxes, the left edge of the first child is placed at the left side, with all extra space placed after the last child. For reverse direction boxes, the right edge of the last child is placed at the right side, with all extra space placed before the first child.
end
For normal direction boxes, the right edge of the last child is placed at the right side, with all extra space placed before the first child. For reverse direction boxes, the left edge of the first child is placed at the left side, with all extra space placed after the last child.
center
The extra space is divided evenly, with half placed before the first child and the other half placed after the last child.
justify
The space is divided evenly in-between each child, with none of the extra space placed before the first child or after the last child. If there is only one child, treat the pack value as if it were start.
    <p style="box-align: center; box-pack: center; width: 300px; height: 300px;">
      <button>centered</button>
    </p>

In the example above, the button is centered within the box using the ‘box-align’ and ‘box-pack’ properties together. The former centers the button vertically, and the latter centers the button horizontally.

7 Multiple Lines

Name: | box-lines
Value: | single | multiple
Initial: | single
Applies to: | box elements
Inherited: | no
Percentages: | no
Media: | visual
Computed value: | specified value

By default a horizontal box will lay out its children in a single row, and a vertical box will lay out its children in a single column. This behavior can be changed using the box-lines property. The default value is single, which means that all elements will be placed in a single row or column, and any elements that don't fit will simply be considered overflow.

If a value of multiple is specified, however, then the box is allowed to expand to multiple lines (that is, multiple rows or columns) in order to accommodate all of its children. The box must attempt to fit its children on as few lines as possible by shrinking all elements down to their minimum widths or heights if necessary.

If the children in a horizontal box still do not fit on a line after being reduced to their minimum widths, then children are moved one by one onto a new line, until the elements remaining on the previous line fit. This process can repeat to an arbitrary number of lines. If a line contains only a single element that doesn't fit, then the element should stay on that line and overflow out of the box. The later lines are placed below the earlier lines in normal direction boxes and above in reverse direction boxes. The height of a line is the height of the largest child in that line. No additional space appears between the lines apart from the margins on the largest elements in each line. For calculating the height of a line, margins with a computed value of auto should be treated as having a value of 0.

A similar process occurs for children in a vertical box. Later lines in normal direction boxes are placed to the right of earlier lines and to the left in reverse direction boxes.

Once the number of lines has been determined, elements with a computed value for box-flex other than 0 stretch as necessary in an attempt to fill the remaining space on the lines. Each line computes flexes independently, so only elements on that line are considered when evaluating flex and flex-groups. The packing of elements in a line, as specified by the box-pack property, is also computed independently for each line.

This example shows four buttons that do not fit horizontally.

    #div1 {
      display: box;
      box-lines: multiple;
      width: 300px;
    }
    button {
      box-flex: 1.0;
      width: 100px;
    }

    <div id="div1">
      <button id="button1">Elephant</button>
      <button id="button2">Tiger</button>
      <button id="button1">Antelope</button>
      <button id="button2">Wildebeest</button>
    </div>

The buttons are shrunk to their minimum widths, in this case calculated intrinsically. Assume that the four buttons have a minimum intrinsic width of 80 pixels. This will allow the first three buttons to fit in 240 pixels with 60 pixels left over of remaining space. Because the box-lines property has a specified value of multiple, the fourth button may be moved onto a second line.

Flexibility is applied to each element, separately for each line. The first line has 60 pixels of remaining space, so each of the three buttons on that line will receive 20 pixels of extra width. The remaining button on a line of its own will stretch to the entire width of the containing box, or 300 pixels.

If the box was resized, the buttons may rearrange onto different lines as necessary. If the style rules in the example above were changed to the following:

    #div1 {
      display: box;
      box-lines: multiple;
      box-pack: center;
      width: 300px;
    }
    button {
      box-flex: 1.0;
      width: 90px;
      max-width: 90px;
    }

Now, each of the buttons will only stretch to include an additional 10 pixels of width, as the maximum width of 90 pixels is only 10 pixels larger than the minimum intrinsic width of the buttons. The remaining 30 pixels of space left over is divided up and placed inside the box outside of the buttons, as the value of box-pack is center. The fourth button will also appear at 90 pixels wide, centered within the box.

7.1 Multiple Lines and alignment

Note: not sure what this should do yet.

The box-align property may be used to control the alignment of children in multiple line boxes, as with single line boxes. If box-align is start, the first line is placed along the top or left edge of the box (or the bottom or right edge for reverse direction boxes), and additional lines are placed afterward with no extra spacing between them. Each element within a line is placed with that same edge aligned. For instance, in a normal direction, vertical box, the top edges of each element are aligned with the top edge of the line it is within. If box-align is end, the first line is placed along the bottom or right edge of the box (or the top or left edge for reverse direction boxes), and additional lines are placed before. Each element within a line is placed with that same edge aligned.

If box-align is center, the extra spacing is divided evenly on both sides of the box, and the lines placed between this space. Elements are centered within their lines. If box-align is baseline, the elements in a line are aligned by their baselines as with single line boxes, with space placed before or after each element in the line as necessary. The first line is placed as with the value start.

If box-align is stretch, then each line is stretched equally, and the elements within each line are stretched to the size of the largest item in that line.

8 Relationship to Inlines and blocks

A box placed in a block is considered a block level element and will be positioned and sized according to the rules for CSS 2.1 (section 10.3 for widths). Specifically, the following equation applies for calculating the width:

‘margin-left’ + ‘border-left-width’ + ‘padding-left’ + ‘width’ + ‘padding-right’ + ‘border-right-width’ + ‘margin-right’ + scrollbar width (if any) = width of containing block

All children of ‘box’ elements are block-level. If inline-level elements are nested inside boxes, they get wrapped in an anonymous block which then takes part in the box layout.

If the width of a child of a flexible box is computed as ‘auto’, then the used value is the shrink-to-fit width. This calculation is done similarly to how the width of a floating element is determined. Otherwise if the width has a computed value, then that value is used as the width.

In a horizontally oriented box, the flexibility is then applied which may increase or decrease the used width. In a vertically oriented box, the position and size of the child may be adjusted by the value of the container's ‘box-align’ property.

The ‘min-width’, ‘min-height’, ‘max-width’, and ‘max-height’ CSS properties act the same on boxes as on blocks.

The height of a child of a flexible box is determined in the same manner as specified in the CSS specification. The used height may further be adjusted by the container's ‘box-align’ property in a horizontally oriented box, or the flexibility in a vertically oriented box.

Note that it is possible for a horizontally oriented box that the height of a flexible child containing an inline descendant will change when the flexibility is applied. Similarly, in a vertically oriented box, the height of a child may change based on the ‘box-align’ property of the box.

Note: more details are needed here, and the relationship with other CSS constructs is yet to be defined.

Acknowledgments

[This section will contain further acknowledgments.]

Thanks for feedback from Shinichiro Hamaji.

References

Normative references

[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 23 April 2009. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2009/CR-CSS2-20090423/

Index

  • box-align, 4
  • box-direction, 3
  • box-flex, 5
  • box-flex-group, 5
  • box-lines, 7
  • box-ordinal-group, 3
  • box-orient, 2
  • box-pack, 6
  • flex groups, 5
  • flexible, 5
  • inflexible, 5
  • ordinal groups, 3

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
box-align | start | end | center | baseline | stretch | stretch | box elements | no | no | visual
box-direction | normal | reverse | inherit | normal | box elements | no | no | visual
box-flex | <number> | 0.0 | in-flow children of box elements | no | no | visual
box-flex-group | <integer> | 1 | in-flow children of box elements | no | no | visual
box-lines | single | multiple | single | box elements | no | no | visual
box-ordinal-group | <integer> | 1 | children of box elements | no | no | visual
box-orient | horizontal | vertical | inline-axis | block-axis | inherit | inline-axis | box elements | no | no | visual
box-pack | start | end | center | justify | start | box elements | no | no | visual


CSS3 Fonts Module

CSS Fonts Module Level 3

W3C Working Draft 18 June 2009

This version:
http://www.w3.org/TR/2009/WD-css3-fonts-20090618
Latest version:
http://www.w3.org/TR/css3-fonts/
Latest editor's draft:
http://dev.w3.org/csswg/css3-fonts/
Previous version (CSS3 Fonts):
http://www.w3.org/TR/2002/WD-css3-fonts-20020802
Previous version (CSS3 Web Fonts):
http://www.w3.org/TR/2002/WD-css3-webfonts-20020802
Editor:
John Daggett (Mozilla)

Copyright © 2009 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

This CSS3 module describes how font properties are specified and how font resources are loaded dynamically. The contents of this specification are a consolidation of content previously divided into CSS3 Fonts and CSS3 Web Fonts modules.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css3-fonts” in the subject, preferably like this: “[css3-fonts] …summary of comment…”

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Table of contents

  • 1 Introduction
  • 2 Typography Background
  • 3 Font properties
    • 3.1 Font family: the ‘font-family’ property
      • 3.1.1 Generic font families
    • 3.2 Font weight: the ‘font-weight’ property
    • 3.3 Font width: the ‘font-stretch’ property
    • 3.4 Font style: the ‘font-style’ property
    • 3.5 Small caps: the ‘font-variant’ property
    • 3.6 Font size: the ‘font-size’ property
    • 3.7 Relative sizing: the ‘font-size-adjust’ property
    • 3.8 Shorthand font property: the ‘font’ property
  • 4 Font resources
    • 4.1 The @font-face rule
    • 4.2 Font family: the ‘font-family’ descriptor
    • 4.3 Font reference: the ‘src’ descriptor
    • 4.4 Font property descriptors: the ‘font-style’, ‘font-weight’, ‘font-stretch’ descriptors
    • 4.5 Character range: the ‘unicode-range’ descriptor
  • 5 Font matching algorithm
  • Appendix A: Mapping font features to CSS properties
  • Appendix B: Font licensing issues
  • Acknowledgments
  • References
    • Normative
    • Informative
  • Index
  • Property index

1 Introduction

A font provides a resource containing the visual representation of characters. At a minimum it contains information that maps character codes to shapes (called glyphs) for displaying these characters. Fonts sharing a common design style are commonly grouped into font families classified by a set of standard font properties. Within a family, the shape displayed for a given character can vary by stroke weight, slant or relative width, among others. A given font face is described by a unique combination of these properties. For a given range of text, CSS font properties are used to select a font family and a specific font face within that family to be used when rendering that text. As a simple example, to use the bold form of Helvetica one could use:

body {
    font-family: Helvetica;
    font-weight: bold;
}

Font resources may be local, installed on the system on which a user agent is running, or downloadable. For local font resources descriptive information can be obtained directly from the font resource. For downloadable font resources (sometimes referred to as web fonts), the descriptive information is included with the reference to the font resource.

Families of fonts typically don't contain a single face for each possible variation of font properties. The CSS font selection mechanism describes how to match a given set of CSS font properties to a given font face.

2 Typography Background

This section is included as background for some of the problems and situations that are described in other sections. It should be viewed as informative only.

Typographic traditions vary across the globe so there is no unique way to classify all fonts across languages and cultures. For even common Latin letters, wide variations are possible:

variations in glyphs for a single character

One character, many glyph variations

Differences in the anatomy of letterforms is one way to distinguish fonts. For Latin fonts, flourishes at the ends of a character's main strokes, or serifs, can distinguish a font from those without. Similar comparisons exist in non-Latin fonts between fonts with tapered strokes and those using primarily uniform strokes:

serif vs. non-serifs

Letterforms with and without serifs

serif vs. non-serifs for japanese

Similar groupings for Japanese typefaces

Fonts contain letterforms and the data needed to map characters to these letterforms. Often this may be a simple one-to-one mapping but more complex mappings are also possible. The use of combining diacritic marks creates many variations for an underlying letterform:

Variations with diacritic marks

A sequence of characters can be represented by a single glyph known as a ligature:

example of a fi ligature

Ligature example

Visual transformations based on textual context like this may be a stylistic option for European languages but are required to correctly render languages like Arabic; the lam and alef characters below must be combined when they exist in sequence:

lam alef ligature

Required Arabic ligature

The relative complexity of these shaping transformations requires additional data within the font.

Sets of font faces with various stylistic variations are often grouped together into font families. In the simplest case a regular face is supplemented with bold and italic faces but much more extensive groupings are possible. Variations in the thickness of letterform strokes, or the weight, or the overall proportions of the letterform, or the width, are most common. In the example below, each letter uses a different font face within the Univers font family. The width used increases from top to bottom and the weight increases from left to right:

various width and weight variations within a single family

Weight and width variations within a single font family

Creating fonts that support multiple scripts is a difficult task; designers need to understand the cultural traditions surrounding the use of type in different scripts and come up with letterforms that somehow share a common theme. Many languages often share a common script and each of these languages may have noticeable stylistic differences. The Arabic script is shared by Persian and Urdu and Cyrillic is used with many languages, not just Russian.

Fonts provide a character map that details the set of characters for they have glyphs. If a document contains characters not supported by a specified font, a user agent may revert to a system font fallback procedure to find glyphs to render these characters correctly. If no font can be found, some form of "missing glyph" character is rendered by the user agent. Often these are the result of authors failing to explicitly indicate the encoding used by a document.

3 Font properties

The particular font face used to render a character is determined by the font family and other font properties that apply to a given element. This structure allows settings to be varied independent of each other.

3.1 Font family: the ‘font-family’ property

Name: | font-family
Value: | [[ <family-name> | <generic-family> ] [, <family-name>| <generic-family>]* ] | inherit
Initial: | depends on user agent
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | as specified

This property specifies a prioritized list of font family names or generic family names. A user agent iterates through the list of family names until it matches an available font that contains a glyph for the character to be rendered. This allows for differences in available fonts across across platforms and for differences in the range of characters supported by individual fonts.

A font family name only specifies a name given to a set of font faces, it does not specify an individual face. Given the availability of the fonts below, Futura would match but Futura Medium would not:

family and face names

Family and individual face names

Some font formats support the use of multiple family names for different localizations. User agents should recognize any of these names independent of the underlying platform localization, system API used or document encoding:

examples of localized family names

Localized family names

Consider the example below:

body {
    font-family: Helvetica, Verdana, sans-serif;
}

If Helvetica is available it will be used when rendering. If neither Helvetica or Verdana is present, then the user agent defined sans serif font will be used.

There are two types of font family names:

<family-name>
The name of a font family of choice such as Helvetica or Verdana in the previous example. Font family names containing more than one word should be quoted. If quoting is omitted, whitespace characters before and after the font family name are ignored and any sequence of whitespace characters inside the font name is converted to a single space. Depending upon the font format used, font family names may be case-sensitive.
<generic-family>
The following generic family keywords are defined: ‘serif’, ‘sans-serif’, ‘cursive’, ‘fantasy’, and ‘monospace’. These keywords can be used as a general fallback mechanism when an author's desired font choices are not available. As keywords, they should not be quoted. Authors are encouraged to append a generic font family as a last alternative for improved robustness.

3.1.1 Generic font families

All five generic font families are defined to exist in all CSS implementations (they need not necessarily map to five distinct actual fonts). User agents should provide reasonable default choices for the generic font families, which express the characteristics of each family as well as possible within the limits allowed by the underlying technology. User agents are encouraged to allow users to select alternative choices for the generic fonts.

serif

Glyphs of serif fonts, as the term is used in CSS, have finishing strokes, flared or tapering ends, or have actual serifed endings (including slab serifs). Serif fonts are typically proportionately-spaced. They often display a greater variation between thick and thin strokes than fonts from the ‘sans-serif’ generic font family. CSS uses the term ‘serif’ to apply to a font for any script, although other names may be more familiar for particular scripts, such as Mincho (Japanese), Sung or Song (Chinese), Batang (Korean). Any font that is so described may be used to represent the generic ‘serif’ family.

sample serif fonts

Sample serif fonts

sans-serif

Glyphs in sans-serif fonts, as the term is used in CSS, have stroke endings that are plain -- without any flaring, cross stroke, or other ornamentation. Sans-serif fonts are typically proportionately-spaced. They often have little variation between thick and thin strokes, compared to fonts from the ‘serif’ family. CSS uses the term ‘sans-serif’ to apply to a font for any script, although other names may be more familiar for particular scripts, such as Gothic (Japanese), Kai (Chinese), or Gulim (Korean). Any font that is so described may be used to represent the generic ‘sans-serif’ family.

sample sans-serif fonts

Sample sans-serif fonts

cursive

Glyphs in cursive fonts generally have either joining strokes or other cursive characteristics beyond those of italic typefaces. The glyphs are partially or completely connected, and the result looks more like handwritten pen or brush writing than printed letterwork. Some scripts, such as Arabic, are almost always cursive. CSS uses the term ‘cursive’ to apply to a font for any script, although other names such as Chancery, Brush, Swing and Script are also used in font names.

sample cursive fonts

Sample cursive fonts

fantasy

Fantasy fonts are primarily decorative fonts that contain playful representations of characters. These do not include Pi or Picture fonts which do not represent actual characters.

sample fantasy fonts

Sample fantasy fonts

monospace

The sole criterion of a monospace font is that all glyphs have the same fixed width. This is often used to render samples of computer code.

sample monospace fonts

Sample monospace fonts

3.2 Font weight: the ‘font-weight’ property

Name: | font-weight
Value: | normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit
Initial: | normal
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | see description

The ‘font-weight’ property specifies weight of glyphs in the font, their degree of blackness or stroke thickness.

Values have the following meanings:

100 to 900
These values form an ordered sequence, where each number indicates a weight that is at least as dark as its predecessor. These roughly correspond to the commonly used weight names below:
  • 100 - Thin
  • 200 - Extra Light (Ultra Light)
  • 300 - Light
  • 400 - Normal
  • 500 - Medium
  • 600 - Semi Bold (Demi Bold)
  • 700 - Bold
  • 800 - Extra Bold (Ultra Bold)
  • 900 - Black (Heavy)
normal
Same as ‘400’.
bold
Same as ‘700’.
bolder
Specifies the weight of the face bolder than the inherited value.
lighter
Specifies the weight of the face lighter than the inherited value.

Font formats that use a scale other than a nine step scale should map their scale onto the CSS scale so that 400 roughly corresponds with a face that would be labeled as Regular, Book, Roman and 700 roughly matches a face that would be labeled as Bold. Or weights may be inferred from the style names, ones that correspond roughly with the scale above. The scale is relative, so a face with a larger weight value should never appear lighter. If style names are used to infer weights, care should be taken to handle variations in style names across locales.

Quite often there are only a few weights available for a particular font family. When a weight is specified for which no face exists, a face with a nearby weight is used. In general, bold weights map to faces with heavier weights and light weights map to faces with lighter weights (see the font matching section below for a precise definition). The examples here illustrate which face is used for different weights, grey indicates a face for that weight does not exist so a face with a nearby weight is used:

weight mappings for a family with 400, 700 and 900 weights

Weight mappings for a font family with 400, 700 and 900 weight faces

weight mappings for a family with 300, 600 weights

Weight mappings for a font family with 300 and 600 weight faces

Although not well-loved by typographers, bold faces are often synthesized by user agents for faces that lack actual bold faces. For the purposes of style matching, these faces should be treated as if they exist within the family.

Values of ‘bolder’ and ‘lighter’ indicate values relative to the weight of the parent element. Based on the inherited weight value, the weight used is calculated using the chart below. Child elements inherit the calculated weight, not a value of ‘bolder’ or ‘lighter’.

Inherited value | bolder | lighter
100 | 400 | 100
200 | 400 | 100
300 | 400 | 100
400 | 700 | 100
500 | 700 | 100
600 | 900 | 400
700 | 900 | 400
800 | 900 | 700
900 | 900 | 700

The table above is equivalent to selecting the next relative bolder or lighter face, given a font family containing normal and bold faces along with a thin and a heavy face. Authors who desire finer control over the exact weight values used for a given element should use numerical values instead of relative weights.

3.3 Font width: the ‘font-stretch’ property

Name: | font-stretch
Value: | normal | wider | narrower | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | inherit
Initial: | normal
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | as specified

The ‘font-stretch’ property selects a normal, condensed, or expanded face from a font family. Absolute keyword values have the following ordering, from narrowest to widest:

  • Ultra Condensed
  • Extra Condensed
  • Condensed
  • Semi Condensed
  • Normal
  • Semi Expanded
  • Expanded
  • Extra Expanded
  • Ultra Expanded

The scale is relative, so a face with a font-stretch value higher in the list above should never appear wider. When a face does not exist for a given width, normal or condensed values map to a narrower face, otherwise a wider face. Conversely, expanded values map to a wider face, otherwise a narrower face. The figure below shows how the nine font-stretch property settings affect font selection for font family containing a variety of widths, grey indicates a width for which no face exists and a different width is substituted:

width mappings for a family with condensed, normal and expanded faces

Width mappings for a font family with condensed, normal and expanded width faces

Values of ‘wider’ and ‘narrower’ indicate values relative to the width of the parent element. Based on the inherited font-stretch value, the width used is calculated using the chart below. Child elements inherit the calculated width value, not a value of ‘wider’ or ‘narrower’.

Inherited value | wider | narrower
ultra-condensed | normal | condensed
extra-condensed | normal | condensed
condensed | normal | condensed
semi-condensed | normal | condensed
normal | expanded | condensed
semi-expanded | expanded | normal
expanded | expanded | normal
extra-expanded | expanded | normal
ultra-expanded | expanded | normal

Issue: relative width values wider, narrower are being considered for removal.

3.4 Font style: the ‘font-style’ property

Name: | font-style
Value: | normal | italic | oblique | inherit
Initial: | normal
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | as specified

The ‘font-style’ property allows italic or oblique faces to be selected. Italic forms are generally cursive in nature while oblique faces are typically sloped versions of the regular face. Oblique faces can be simulated by artificially sloping the glyphs of the regular face. Compare the artificially sloped renderings of Palatino ‘a’ and Baskerville ‘N’ in grey with the actual italic versions:

artificial sloping vs. real italics

Artificial sloping versus real italics

A value of ‘normal’ selects a face that is classified as ‘normal’, while ‘oblique’ selects a font that is labeled ‘oblique’. A value of ‘italic’ selects a font that is labeled ‘italic’, or, if that is not available, one labeled ‘oblique’. If no italic or oblique faces is available, an oblique face can by synthesized by rendering the normal face with a sloping transformation applied.

Many scripts lack the tradition of mixing a cursive form within text rendered with a normal face. Chinese, Japanese and Korean fonts almost always lack italic or oblique faces. Fonts that support a mixture of scripts will sometimes omit specific scripts such as Arabic from the set of glyphs supported in the italic face. User agents should be careful about making character map assumptions across faces.

3.5 Small caps: the ‘font-variant’ property

Name: | font-variant
Value: | normal | small-caps | inherit
Initial: | normal
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | as specified
  • small-caps
  • used to select alternate glyphs if available in font
  • can be simulated using sized versions of uppercase glyphs

In a small-caps font, the glyphs for lowercase letters look similar to the uppercase ones, but in a smaller size and with slightly different proportions. The ‘font-variant’ property requests such a font for bicameral (having two cases, as with Latin script). This property has no visible effect for scripts that are unicameral (having only one case, as with most of the world's writing systems). Values have the following meanings:

normal
Specifies a face that is not labeled as a small-caps font.
small-caps
Specifies a font that is labeled as a small-caps font. If a genuine small-caps font is not available, user agents should simulate a small-caps font, for example by taking a normal font and replacing the lowercase letters by scaled uppercase characters. As a last resort, unscaled uppercase letter glyphs in a normal font may replace glyphs in a small-caps font so that the text appears in all uppercase letters.

Example(s):

The following example results in an h3 element in small-caps, with emphasized words em in oblique small-caps:

h3 { font-variant: small-caps }
em { font-style: oblique }

Insofar as this property causes text to be transformed to uppercase, the same considerations as for ‘text-transform’ apply.

3.6 Font size: the ‘font-size’ property

Name: | font-size
Value: | <absolute-size> | <relative-size> | <length> | <percentage> | inherit
Initial: | medium
Applies to: | all elements
Inherited: | yes
Percentages: | refer to parent element's font size
Media: | visual
Computed value: | absolute length

This property indicates the desired height of glyphs from the font. For scalable fonts, the font-size is a scale factor applied to the EM unit of the font. (Note that certain glyphs may bleed outside their EM box.) For non-scalable fonts, the font-size is converted into absolute units and matched against the declared font-size of the font, using the same absolute coordinate space for both of the matched values. Values have the following meanings:

<absolute-size>
An <absolute-size> keyword refers to an entry in a table of font sizes computed and kept by the user agent. Possible values are:

[ xx-small | x-small | small | medium | large | x-large | xx-large ]

<relative-size>
A <relative-size> keyword is interpreted relative to the table of font sizes and the font size of the parent element. Possible values are:

[ larger | smaller ]

For example, if the parent element has a font size of ‘medium’, a value of ‘larger’ will make the font size of the current element be ‘large’. If the parent element's size is not close to a table entry, the user agent is free to interpolate between table entries or round off to the closest one. The user agent may have to extrapolate table values if the numerical value goes beyond the keywords.

<length>
A length value specifies an absolute font size (that is independent of the user agent's font table). Negative lengths are illegal.
<percentage>
A percentage value specifies an absolute font size relative to the parent element's font size. Use of percentage values, or values in ‘em’s, leads to more robust and cascadable style sheets.

The following table provides user agent's guideline for the absolute-size scaling factor and their mapping to XHTML heading and absolute font-sizes. The ‘medium’ value is used as the reference middle value. The user agent may fine tune these values for different fonts or different types of display devices.

CSS absolute-size values | xx-small | x-small | small | medium | large | x-large | xx-large |
scaling factor | 3/5 | 3/4 | 8/9 | 1 | 6/5 | 3/2 | 2/1 | 3/1
XHTML headings | h6 |  | h5 | h4 | h3 | h2 | h1 |
XHTML font sizes | 1 |  | 2 | 3 | 4 | 5 | 6 | 7

Note 1. To preserve readability, an UA applying these guidelines should nevertheless avoid creating font-size resulting in less than 9 pixels per EM unit on a computer display .

Note 2. In CSS1, the suggested scaling factor between adjacent indexes was 1.5 which user experience proved to be too large. In CSS2, the suggested scaling factor for computer screen between adjacent indexes was 1.2 which still created issues for the small sizes. The new scaling factor varies between each index to provide a better readability.

The actual value [link to Cascading module] of this property may differ from the computed value due a numerical value on ‘font-size-adjust’ and the unavailability of certain font sizes.

Child elements inherit the computed ‘font-size’ value (otherwise, the effect of ‘font-size-adjust’ would compound).

POWERED BY HeroNote

Example(s):

p { font-size: 12pt; }
blockquote { font-size: larger }
em { font-size: 150% }
em { font-size: 1.5em }

3.7 Relative sizing: the ‘font-size-adjust’ property

Name: | font-size-adjust
Value: | <number> | none | inherit
Initial: | none
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | as specified

For any given font size, the apparent size and legibility of text varies across fonts. For scripts such as Latin or Cyrillic that distinguish between upper and lowercase letters, the relative height of lowercase letters compared to their uppercase counterparts is a determining factor of legibility. This is commonly referred to as the aspect value. Precisely defined, it is equal to the x-height of a font divided by the font size.

In situations where font fallback occurs, fallback fonts may not share the same aspect ratio as the desired font family and will thus appear less readable. The font-size-adjust property is a way to preserve the readability of text when font fallback occurs. It does this by adjusting the font-size so that the x-height is the same irregardless of the font used.

The style defined below defines Verdana as the desired font family, but if Verdana is not available Futura or Times will be used.

p {
    font-family: Verdana, Futura, Times;
}

<p>Lorem ipsum dolor sit amet, ...</p>

Verdana has a relatively high aspect ratio, lowercase letters are relatively tall compared to uppercase letters, so at small sizes text appears legible. Times has a lower aspect ratio and so if fallback occurs, the text will be less legible at small sizes than Verdana.

How text rendered in each of these fonts compares is shown below, the columns show text rendered in Verdana, Futura and Times. The same font-size value is used across cells within each row and red lines are included to show the differences in x-height. In the upper half each row is rendered in the same font-size value. The same is true for the lower half but in this half the font-size-adjust property is also set so that the actual font size is adjusted to perserve the x-height across each row. Note how small text remains relatively legible across each row in the lower half.

text with and without font-size-adjust

Text with and without the use of font-size-adjust

This property allows authors to specify an aspect value for an element that will effectively preserve the x-height of the first choice font, whether it is substituted or not. Values have the following meanings:

none
Do not preserve the font's x-height.
<number>
Specifies the aspect value used in the calculation below to calculate the adjusted font size:
c  =  ( a / a' ) s

where:

s  =  font-size value
a  =  aspect value as specified by the font-size-adjust property
a' =  aspect value of actual font
c  =  adjusted font-size to use

This value applies to any font that is selected but in typical usage it should be based on the aspect value of the first font in the font-family list. If this is specified accurately, the (a/a') term in the formula above is effectively 1 for the first font and no adjustment occurs. If the value is specified inaccurately, text rendered using the first font in the family list will display differently in older user agents that don't support font-size-adjust.

Authors can calculate the aspect value for a given font by comparing spans with the same content but different font-size-adjust properties. If the same font-size is used, the spans will match when the font-size-adjust value is accurate for the given font.

Two spans with borders are used to determine the aspect value of a font. The font-size is the same for both spans but the font-size-adjust property is specified only for the right span. Starting with a value of 0.5, the aspect value can be adjusted until the borders around the two letters line up.

p {
    font-family: Futura;
    font-size: 500px;
}

span {
    border: solid 1px red;
}

.adjust {
    font-size-adjust: 0.5;
}

<p><span>b</span><span class="adjust">b</span></p>
Futura with an aspect value of 0.5

Futura with an aspect value of 0.5

The box on the right is a bit bigger than the one on the left, so the aspect value of this font is something less than 0.5. Adjust the value until the boxes align.

3.8 Shorthand font property: the ‘font’ property

Name: | font
Value: | [ [ <‘font-style’> || <‘font-variant’> || <‘font-weight’> ]? <‘font-size’> [ / <‘line-height’> ]? <‘font-family’> ] | caption | icon | menu | message-box | small-caption | status-bar | inherit
Initial: | see individual properties
Applies to: | all elements
Inherited: | yes
Percentages: | see individual properties
Media: | visual
Computed value: | see individual properties

The ‘font’ property is, except as described below, a shorthand property for setting ‘font-style’, ‘font-variant’, ‘font-weight’, ‘font-size’, ‘line-height’, and ‘font-family’, at the same place in the style sheet. The syntax of this property is based on a traditional typographical shorthand notation to set multiple properties related to fonts.

All font-related properties are first reset to their initial values, including those listed in the preceding paragraph plus ‘font-stretch’ and ‘font-size-adjust’. Then, those properties that are given explicit values in the ‘font’ shorthand are set to those values. For a definition of allowed and initial values, see the previously defined properties. For reasons of backwards compatibility, it is not possible to set ‘font-stretch’ and ‘font-size-adjust’ to other than their initial values using the ‘font’ shorthand property; instead, set the individual properties.

Example(s):

p { font: 12pt/14pt sans-serif }
p { font: 80% sans-serif }
p { font: x-large/110% "new century schoolbook", serif }
p { font: bold italic large Palatino, serif }
p { font: normal small-caps 120%/120% fantasy }
p { font: oblique 12pt "Helvetica Nue", serif; font-stretch: condensed }

In the second rule, the font size percentage value (‘80%’) refers to the font size of the parent element. In the third rule, the line height percentage (‘110%’) refers to the font size of the element itself.

The first three rules do not specify the ‘font-variant’ and ‘font-weight’ explicitly, so these properties receive their initial values so this property receives its initial value (‘normal’). Notice that the font family name "new century schoolbook", which contains spaces, is enclosed in quotes. The fourth rule sets the ‘font-weight’ to ‘bold’, the ‘font-style’ to ‘italic’, and implicitly sets ‘font-variant’ to ‘normal’.

The fifth rule sets the ‘font-variant’ (‘small-caps’), the ‘font-size’ (120% of the parent's font size), the ‘line-height’ (120% of the font size) and the ‘font-family’ (‘fantasy’). It follows that the keyword ‘normal’ applies to the two remaining properties: ‘font-style’ and ‘font-weight’.

The sixth fifth rule sets the ‘font-style’, ‘font-size’, and ‘font-family’, the other font properties being set to their initial values. It then sets ‘font-stretch’ to ‘condensed’ since that property cannot be set to that value using the ‘font’ shorthand property.

The following values refer to system fonts:

caption
The font used for captioned controls (e.g., buttons, drop-downs, etc.).
icon
The font used to label icons.
menu
The font used in menus (e.g., dropdown menus and menu lists).
message-box
The font used in dialog boxes.
small-caption
The font used for labeling small controls.
status-bar
The font used in window status bars.

System fonts may only be set as a whole; that is, the font family, size, weight, style, etc. are all set at the same time.These values may then be altered individually if desired. If no font with the indicated characteristics exists on a given platform, the user agent should either intelligently substitute (e.g., a smaller version of the ‘caption’ font might be used for the ‘smallcaption’ font), or substitute a user agent default font. As for regular fonts, if, for a system font, any of the individual properties are not part of the operating system's available user preferences, those properties should be set to their initial values.

That is why this property is "almost" a shorthand property: system fonts can only be specified with this property, not with ‘font-family’ itself, so ‘font’ allows authors to do more than the sum of its subproperties. However, the individual properties such as ‘font-weight’ are still given values taken from the system font, which can be independently varied.

Example(s):

button { font: 300 italic 1.3em/1.7em "FB Armada", sans-serif }
button p { font: menu }
button p em { font-weight: bolder }

If the font used for dropdown menus on a particular system happened to be, for example, 9-point Charcoal, with a weight of 600, then P elements that were descendants of BUTTON would be displayed as if this rule were in effect:

button p { font: 600 9pt Charcoal }

Because the ‘font’ shorthand resets to its initial value any property not explicitly given a value, this has the same effect as this declaration:

button p {
  font-style: normal;
  font-variant: normal;
  font-weight: 600;
  font-size: 9pt;
  line-height: normal;
  font-family: Charcoal
}

4 Font resources

4.1 The @font-face rule

The @font-face rule allows for linking to fonts that are automatically activated when needed. This permits authors to work around the limitation of "web-safe" fonts, allowing for consistent rendering independent of the fonts available in a given user's environment. A set of font descriptors define the location of a font resource, either locally or externally, and the style characteristics of an individual face. Multiple @font-face rules can be used to construct font families with a variety of faces. Using CSS font matching rules, a user agent can selectively download only those faces that are needed for a given piece of text.

The general form of an @font-face at-rule is:

@font-face { <font-description> }

where <font-description> has the form:

descriptor: value;
descriptor: value;
[...]
descriptor: value;

Each @font-face rule specifies a value for every font descriptor, either implicitly or explicitly. Those not given explicit values in the rule take the initial value listed with each descriptor in this specification. These descriptors apply solely within the context of the @font-face rule in which they are defined, and do not apply to document language elements. There is no notion of which elements the descriptors apply to or whether the values are inherited by child elements. When a given descriptor occurs multiple times in a given @font-face rule, only the last specified value is used, all prior values for that descriptor are ignored.

To use a downloadable font called Gentium:

@font-face {
  font-family: Gentium;
  src: url(http://site/fonts/Gentium.ttf);
}

p { font-family: Gentium, serif; }

The user agent will download Gentium and use it when rendering text within paragraph elements. If for some reason the site serving the font is unavailable, the default serif font will be used.

A given set of @font-face rules define a set of fonts available to containing documents. Multiple rules can be used to define a family with a large set of faces. When font matching is done fonts defined using these rules are considered before other available fonts on a system.

Downloaded fonts are only available to documents that reference them, they should not be made available to other applications or other documents. User agent implementors might consider it convenient to use downloaded fonts when rendering characters in other documents for which no other available font exists as part of the system font fallback procedure. This however leads to non-deterministic rendering patterns where the appearance of a page effectively becomes a function of browsing history.

User agents which do not understand the @font-face rule encounter the opening curly bracket and ignore forward until the closing curly bracket. This at-rule conforms with the forward-compatible parsing requirement of CSS, parsers may ignore these rules without error. Any descriptors that are not recognized or implemented by a given user agent must be ignored. @font-face rules require a font-family and src descriptor, if either of these are missing the @font-face should be ignored.

In cases where user agents have limited platform resources or implement the ability to disable downloadable font resources, @font-face rules should simply be ignored; the behavior of individual descriptors as defined in this specification should not be altered.

4.2 Font family: the ‘font-family’ descriptor

Name: | font-family
Value: | <family-name>
Initial: | N/A

This descriptor defines the font family name that will be used in all CSS font family name matching, overriding font family names contained in the underlying font data. If the font family name is the same as a font family available in a given user's environment, it effectively hides the underlying font for documents that use the stylesheet. This permits a web author to freely choose font-family names without worrying about conflicts with font family names present in a given user's environment. Errors loading font data do not affect font name matching behavior. User agents that apply platform font aliasing rules to font family names defined via @font-face rules are considered non-conformant.

4.3 Font reference: the ‘src’ descriptor

Name: | src
Value: | [ <uri> [format(<string> [, <string>]*)] | <font-face-name> ] [, <uri> [format(<string> [, <string>]*)] | <font-face-name> ]*
Initial: | N/A

This descriptor specifies the resource containing font data. It is required, whether the font is downloadable or locally installed. It's value is a prioritized, comma-separated list of external references or locally installed font face names. When a font is needed the user agent iterates over the set of references listed, using the first one it can successfully activate. Fonts containing invalid data are treated as if they were not found, the user agent loads the next font in the list.

External references consist of a URI, followed by an optional hint regarding the format of the font resource referenced by that URI. The format hint contains a comma-separated list of format strings that denote well-known font formats. Conformant user agents should skip downloading a font resource if the format hints indicate only unsupported or unknown font formats. If no format hints are supplied, the user agent should download the font resource.

An initial list of format strings defined by this specification and representing formats likely to be used by implementations on various platforms is:

String | Font Format | Common extensions
"truetype" | TrueType | .ttf
"opentype" | OpenType | .ttf, .otf
"truetype-aat" | TrueType with Apple Advanced Typography extensions | .ttf
"embedded-opentype" | Embedded OpenType | .eot
"svg" | SVG Font | .svg, .svgz

Given the overlap in common usage between TrueType and OpenType, for the purpose of a format hint "truetype" and "opentype" should be considered as synonymous; a format hint of "opentype" does not imply that the font contains Postscript CFF style glyph data or that it contains OpenType layout information (see Appendix A for more background on this). The "truetype-aat" string indicates that a font contains Apple Advanced Typography tables so user agents on platforms that do not support these tables should treat this format as unsupported. This allows authors to provide multiple fonts for rendering complex scripts such as Arabic or Devanagari that require platform-specific font data.

Issue: does a public registry need to be established for these hints?

A full font URI with no format hint:

  src: url(http://site/fonts/font.otf);

Arabic font with different versions for specific platforms:

  src: url(../fonts/LateefRegAAT.ttf) format("truetype-aat"),
       url(../fonts/LateefRegOT.ttf) format("opentype");

A font containing tables to support multiple advanced font formats:

  src: url(DoulosSILR.ttf) format("opentype","truetype-aat");

As with other URIs in CSS, the URI may be partial, in which case it is resolved relative to the location of the style sheet containing the @font-face rule. In the case of SVG fonts, the URL points to an element within a document containing SVG font definitions. If the element reference is omitted, a reference to the first defined font is implied.

The locally installed <font-face-name> is a format-specific string that uniquely identifies a single font face within a larger family. For TrueType and OpenType fonts, the full font name as defined in the font name table is used to reference a given face. Additionally, for TrueType and OpenType fonts user agents may optionally support Postscript name lookup on platforms where that is appropriate. The notation for a <font-face-name> is the unique font face name enclosed by "local(" and ")". The name can optionally be enclosed in quotes. This also allows for referencing faces that belong to larger families that cannot otherwise be referenced. If a font face with a given full font name or Postscript name is not found, the user agent loads the next font in the list, platform substitutions for the font should not be used.

Use the local copy of a font or download it if it's not:

@font-face {
  font-family: Gentium;
  src: local(Gentium), url(/fonts/Gentium.ttf);
}

Use a local font or reference an SVG font in another document:

@font-face {
  font-family: Headline;
  src: local(Futura-Medium),
       url(fonts.svg#MyGeometricModern) format("svg");
}

Create an alias for local Japanese fonts on different platforms:

@font-face {
  font-family: Japanese;
  src: local(HiraKakuPro-W3), local(Meiryo), local(IPAPGothic);
}

Reference a font face that cannot be matched within a larger family:

@font-face {
  font-family: Hoefler Text Ornaments;
  /* has the same font properties as Hoefler Text Regular */
  src: local(HoeflerText-Ornaments);
}

4.4 Font property descriptors: the ‘font-style’, ‘font-weight’, ‘font-stretch’ descriptors

Name: | font-style
Value: | normal | italic | oblique
Initial: | normal
Name: | font-weight
Value: | normal | bold | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900
Initial: | normal
Name: | font-stretch
Value: | normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded
Initial: | normal

These descriptors define the characteristics of a font face and are used in the process of matching styles to specific faces. For a font family defined with several @font-face rules, user agents can either download all faces in the family or use these descriptors to selectively download font faces that match actual styles used in document. The values for these descriptors are the same as those for the corresponding font properties except that relative keywords are not allowed: bolder, lighter, wider, narrower. If these descriptors are omitted, default values are assumed.

The value for these font face style attributes is used in place of the style implied by the underlying font data. This allows authors to combine faces in flexible combinations, even in situations where the original font data was arranged differently. User agents that implement synthetic bolding and obliqueing should only apply synthetic styling in cases where the font descriptors imply this is needed, rather than based on the style attributes implied by the font data.

4.5 Character range: the ‘unicode-range’ descriptor

Name: | unicode-range
Value: | <urange> [, <urange>]*
Initial: | U+0-10FFFF

This descriptor defines the range of Unicode characters supported by a given font. The values of <urange> are expressed using hexadecimal numbers prefixed by "U+", corresponding to Unicode character code points. The unicode-range descriptor serves as a hint for user agents when deciding whether or not to download a font resource.

Unicode range values are written using hexadecimal values and are case insensitive. Each is prefixed by "U+" and multiple, discontinuous ranges are separated by commas. Whitespace before or after commas is ignored. Valid character code values vary between 0 and 10FFFF inclusive. A single range has three basic forms:

  • a single code point (e.g. U+416)
  • an interval value range (e.g. U+400-4ff)
  • a range where trailing ‘?’ characters imply ‘any digit value’ (e.g. U+4??)

Ranges that do not fit any of the above three forms are considered to be parse errors and the descriptor is omitted. Interval ranges consisting of a single code point are valid. Ranges specified with ‘?’ that lack an initial digit (e.g. "U+???") are also valid, and are treated as if there was a single 0 before the question marks (thus, "U+???" = "U+0???" = "U+0000-0FFF"). "U+??????" is not a syntax error, even though "U+0??????" would be. Ranges can overlap but interval ranges that descend (e.g. U+400-32f) are invalid and omitted rather than treated as parse errors; they have no effect on other ranges in a list of ranges. Ranges are clipped to the domain of Unicode code points (currently 0 - 10FFFF inclusive); a range entirely outside the domain is omitted. Without any valid ranges, the descriptor is omitted. User agents may normalize the list of ranges into a list that is different but represents the equivalent set of character code points.

The character range can be a subset of the full character map of the underlying font. The effective unicode-range used when mapping characters to fonts is the intersection of the unicode range specified and the underlying character map of the font. This means that authors do not need to define the unicode-range of a font precisely, broad ranges for which a sparse set of code points are defined in the font can be used. Code points outside of the defined unicode-range are ignored, irregardless of whether the font contains a glyph for that code point or not. User agents that download fonts for characters outside the defined unicode-range are considered non-conformant. Likewise, user agents that render a character using a font resource for which the defined unicode-range does not include that character are also considered non-conformant.

Example ranges for specific languages or characters:

unicode-range: U+A5;
a single code point, the yen/yuan symbol
unicode-range: U+0-7F;
code range for basic ASCII characters
unicode-range: U+590-5ff;
code range for Hebrew characters
unicode-range: U+A5, U+4E00-9FFF, U+30??, U+FF00-FF9F;
code range for Japanese kanji, hiragana and katakana characters plus yen/yuan symbol

The BBC provides news services in a wide variety of languages, many that are not well supported across all platforms. Using an @font-face rule, the BBC could provide a font for any of these languages, as it already does via a manual font download.

@font-face {
  font-family: BBCBengali;
  src: url(fonts/BBCBengali.ttf) format("opentype");
  unicode-range: U+00-FF, U+980-9FF;
}

Technical documents often require a wide range of symbols. The STIX Fonts project is one project aimed at providing fonts to support a wide range of technical typesetting in a standardized way. The example below shows the use of a font that provides glyphs for many of the mathematical and technical symbol ranges within Unicode:

@font-face {
  font-family: STIXGeneral;
  src: local(STIXGeneral), url(/stixfonts/STIXGeneral.otf);
  unicode-range: U+000-49F, U+2000-27FF, U+2900-2BFF, U+1D400-1D7FF;
}

Multiple @font-face rules with different unicode ranges for the same family and style descriptor values can be used to create composite fonts that mix the glyphs from different fonts for different scripts. This can be used to combine fonts that only contain glyphs for a single script (e.g. Latin, Greek, Cyrillic) or it can be used by authors as a way of segmenting a font into fonts for commonly used characters and less frequently used characters. Since the user agent will only pull down the fonts it needs this helps reduce page bandwidth.

If the unicode ranges overlap for a set of @font-face rules with the same family and style descriptor values, the rules are ordered in the reverse order they were defined; the last rule defined is the first to be checked for a given character.

This example shows how an author can override the glyphs used for Latin characters in a Japanese font with glyphs from a different font. The first rule specifies no range so it defaults to the entire range. The range specified in the second rule overlaps but takes precedence because it is defined later.

@font-face {
  font-family: JapaneseWithGentium;
  src: local(MSMincho);
  /* no range specified, defaults to entire range */
}

@font-face {
  font-family: JapaneseWithGentium;
  src: url(../fonts/Gentium.ttf);
  unicode-range: U+0-2FF;
}

Consider a family constructed to optimize bandwidth by separating out Latin, Japanese and other characters into different font files:

/* fallback font - size: 4.5MB */
@font-face {
  font-family: DroidSans;
  src: url(DroidSansFallback.ttf);
  /* no range specified, defaults to entire range */
}

/* Japanese glyphs - size: 1.2MB */
@font-face {
  font-family: DroidSans;
  src: url(DroidSansJapanese.ttf);
  unicode-range: U+3000-9FFF, U+ff??;
}

/* Latin, Greek, Cyrillic along with some
   punctuation and symbols - size: 190KB */
@font-face {
  font-family: DroidSans;
  src: url(DroidSans.ttf);
  unicode-range: U+000-5FF, U+1e00-1fff, U+2000-2300;
}

For simple Latin text, only the font for Latin characters is downloaded:

body { font-family: DroidSans; }

<p>This is that</p>

In this case the user agent first checks the unicode-range for the font containing Latin characters (DroidSans.ttf). Since all the characters above are in the range U+0-5FF, the user agent downloads the font and renders the text with that font.

Next, consider text that makes use of an arrow character (⇨):

<p>This &#x21e8; that<p>

The user agent again first checks the unicode-range of the font containing Latin characters. Since U+2000-2300 includes the arrow code point (U+21E8), the user agent downloads the font. For this character however the Latin font does not have a matching glyph, so the effective unicode-range used for font matching excludes this code point. Next, the user agent evaluates the Japanese font. The unicode-range for the Japanese font, U+3000-9FFF and U+ff??, does not include U+21E8, so the user agent does not download the Japanese font. Next the fallback font is considered. The @font-face rule for the fallback font does not define unicode-range so it's value defaults to the range of all Unicode code points. The fallback font is downloaded and used to render the arrow character.

5 Font matching algorithm

The procedure for choosing fonts consists of iterating over the font families determined by the font-family property, selecting a font face with the appropriate style based on other font properties and then determining whether a glyph exists for a given character. This procedure is performed on each character to be rendered. Optimizations are allowed provided that an implementation behaves as if the algorithm had been followed exactly. Matching occurs in a well-defined order to insure that the results are as consistent as possible across user agents, given an identical set of available fonts and rendering technology.

To begin with, a user agent must determine the set of font families available on a given platform and determine the style characteristics of all faces for each family. If two faces have the exact same style characteristics, one of them is ignored. Fonts available via @font-face rules are referenced per document and are not treated as generally available fonts.

  1. For each character within a given element, the user agent evaluates the font properties applicable. The user agent starts with the first family name in the ‘font-family’ prioritized list.
  2. If the family name is a generic family name, the user agent looks up the appropriate font family name to be used. User agents may choose the generic font family to use based on the language of the containing element or the Unicode range of the character. The user agent attempts to find the family name among fonts defined via @font-face rules and then among available system fonts.
  3. If a font family match occurs, the user agent then attempts to select a face that matches the remaining font properties. It matches these properties in the order given below:
    1. ‘font-stretch’ is tried first. ‘normal’ matches a font not labeled as ‘condensed’ or ‘expanded’.
    2. ‘font-style’ is tried next. ‘italic’ will be satisfied if there is either a face in the UA's font database labeled with the CSS keyword ‘italic’ (preferred) or ‘oblique’. Otherwise the values must be matched exactly or font-style will fail.
    3. ‘font-variant’ is tried next. ‘normal’ matches a font not labeled as ‘small-caps’; ‘small-caps’ matches (1) a font labeled as ‘small-caps’, (2) a font in which the small caps are synthesized, or (3) a font where all lowercase letters are replaced by uppercase letters. A small-caps font may be synthesized by electronically scaling uppercase letters from a normal font.
    4. ‘font-weight’ is matched next, it will never fail. If bolder/lighter relative weights are used, calculate the effective weight based on the inherited weight value, as described in the definition of font-weight above. Given the desired weight and the set of face weights that match the properties above, if the desired weight is available that face matches. Otherwise, a weight is chosen using the rules below:
      • If the desired weight is less than 400, weights below the desired weight are checked in descending order followed by weights above the desired weight in ascending order until a match is found.
      • If the desired weight is greater than 500, weights above the desired weight are checked in ascending order followed by weights below the desired weight in descending order until a match is found.
      • If the desired weight is 400, 500 is checked first and then the rule for desired weights less than 400 is used.
      • If the desired weight is 500, 400 is checked first and then the rule for desired weights less than 400 is used.
    5. ‘font-size’ must be matched within a UA-dependent margin of tolerance. (Typically, sizes for scalable fonts are rounded to the nearest whole pixel, while the tolerance for bitmapped fonts could be as large as 20%.) Further computations, e.g., by ‘em’ values in other properties, are based on the ‘font-size’ value that is used, not the one that is specified.
  4. If no matching face exists or the matched face does not contain a glyph for the character to be rendered, the next family name is selected and the previous two steps repeated. If the matched font is defined via an @font-face rule, the font resource is downloaded. Otherwise if the matched font is defined via @font-face and needs to be downloaded, the user agent can either wait until the font is downloaded or render once with substituted font metrics and render again once the font is downloaded.
  5. If there are no more font families to be evaluated and no matching face has been found, then the user agent performs a system font fallback procedure to find the best match for the character to be rendered. The result of this procedure may vary across user agents.
  6. If a particular character cannot be displayed using any font, the user agent should indicate by some means that a character is not being displayed, either by displaying a symbolic representation of the missing glyph or using the ‘missing character’ glyph from another font.

It's useful to note that the CSS selector syntax may be used to create language-sensitive typography. For example, some Chinese and Japanese characters are unified to have the same Unicode code point, although the abstract glyphs are not the same in the two languages.

*:lang(ja-jp) { font: 900 14pt/16pt "Heisei Mincho W9", serif; }
*:lang(zh-tw) { font: 800 14pt/16.5pt "Li Sung", serif; }

This selects any element that has the given language - Japanese or Traditional Chinese - and uses the appropriate font.

Appendix A: Mapping font features to CSS properties

This section is included as background for some of the problems and situations that are described in other sections. It should be viewed as informative only.

Font properties in CSS are designed to be independent of the underlying font formats used; they can be used to specify bitmap fonts, Type1 fonts, SVG fonts in addition to the common TrueType and OpenType fonts. But there are facets of the TrueType and OpenType formats that often cause confusion for authors and present challenges to implementors on different platforms.

Originally developed at Apple, TrueType was designed as an outline font format for both screen and print. Microsoft joined Apple in developing the TrueType format and both platforms have supported TrueType fonts since then. Font data in the TrueType format consists of a set of tables distinguished with common four-letter tag names, each containing a specific type of data. For example, naming information, including copyright and license information, is stored in the ‘name’ table. The character map (‘cmap’) table contains a mapping of character encodings to glyphs. Apple later added additional tables for supporting enhanced typographic functionality; these are now called Apple Advanced Typography, or AAT, fonts. Microsoft and Adobe developed a separate set of tables for advanced typography and called their format OpenType.

In many cases the font data used under Microsoft Windows or Linux is slightly different from the data used under Apple's Mac OS X because the TrueType format allowed for variation across platforms. This includes font metrics, names and character map data.

Font family names for TrueType and OpenType fonts are contained in the ‘name’ table, in name records with name ID 1. Mulitple names can be stored for different locales but Microsoft recommends fonts always include at least a US English version of the name. On Windows, the family name can only be used for a maximum of four faces; for larger groupings the "preferred family" (name ID 16) or "WWS family" (name ID 21) can be used. The full font name (name ID 4) and the Postscript name (name ID 6) describe a single face uniquely. The bold face of the Gill Sans family has a fullname of "Gill Sans Bold" and a Postscript name of "GillSans-Bold". There can be multiple localized versions of the fullname for a given face but the Postscript name is always a unique name made from a limited set of ASCII characters.

On various platforms, different names are used to search for a font. For example, with the Windows GDI CreateIndirectFont API, either a family or fullname can be used to lookup a face while on Mac OS X the ATSFontFindFromName and ATSFontFindFromPostScriptName API calls are used to lookup a given face using the fullname and Postscript name. Under Linux, the fontconfig API allows fonts to be searched using any of these names. In situations where platform API's automatically substitute other font choices, it may be necessary to verify a returned font matches a given name.

The weight of a given face can be determined via the usWeightClass field of the OS/2 table or inferred from the style name (name ID 2). Likewise, the width can be determined via the usWidthClass of the OS/2 table or inferred from the style name. For historical reasons, font designers have sometimes skewed values in the OS/2 table to work around problems in the Windows GDI API.

Rendering complex scripts that use contextual shaping such as Thai, Arabic and Devanagari requires features present only in OpenType or AAT fonts. Currently, complex script rendering is supported on Windows and Linux using OpenType font features while AAT font features are used under Mac OS X. Apple has indicated it intends support complex script rendering using OpenType font features in the future.

Appendix B: Font licensing issues

The use of fonts on the web is often surrounded in controversy. Font designers expend huge amounts of effort to create their designs, painstakingly refining letterforms and tuning font data to assure that the letterforms appear as desired both in print and on the screen. As a result they often license their fonts very carefully, often with somewhat complex terms. Authors who want to use specific fonts via a downloadable font mechanism must always carefully verify that their intended use is within the scope of the font license. Many commercial fonts presently do not allow web downloading of their fonts in any form. Font formats often store references to the font license within the font data itself. When in doubt, it's best to verify with the font designer directly. Vendors that bundle fonts with their products are also strongly encouraged to carefully explain the license details that covers the fonts they bundle.

An author would like to use Gotham, a font designed by Hoefler & Frere-Jones, as a downloadable font for their webpages. But the end-user license agreement that covers Gotham specifically notes that usage via @font-face rules in CSS style sheets is not allowed. The author cannot link to this font in their web pages.

An author wants to use Gentium, a font developed by SIL International. This font is licensed under the terms of the Open Font License, so as long as the author follows the relatively liberal terms of this license, they can use Gentium as a downloadable font for their web pages.

Acknowledgments

A special thanks to Robert Bringhurst for the sublime mind expansion that is The Elements of Typographic Style.

References

Normative

[UNICODE5]
The Unicode Consortium. The Unicode Standard, Version 5.1.0. Addison-Wesley. 2007. ISBN 0-321-48091-0. URL: http://www.unicode.org/versions/Unicode5.1.0/

Informative

[ARABIC-TYPO]
Huda Smitshuijzen AbiFares. Arabic Typography: A Comprehensive Sourcebook. Saqi Books. 2001. ISBN 0-86356-347-3.
[ELEMTYPO]
Robert Bringhurst. The Elements of Typographic Style, Version 3.1. Hartley & Marks. 2005. ISBN 0-88179-206-3.
[LANGCULTTYPE]
John D. Berry, Ed. Language Culture Type. Graphis. 2001. ISBN 1-932026-01-0.

Index

  • <absolute-size>
    • definition of, 3.6
  • aspect value, 3.7
  • at-rules, 4.1
  • bicameral
    • definition of, 3.5
  • cursive, definition of, #
  • fantasy, definition of, #
  • font, 3.8
  • <font-description>
    • definition of, 4.1
  • @font-face, 4.1, 4.1, 4.3
  • <font-face-name>
    • definition of, 4.3
  • font-family, 3.1, 4.2
  • font-size, 3.6
  • font-size-adjust, 3.7
  • font-stretch, 3.3, 4.4
  • font-style, 3.4, 4.4
  • font-variant, 3.5
  • font-weight, 3.2, 4.4
  • <length>, 3.6
  • monospace, definition of, #
  • <number>, 3.7
  • <percentage>, 3.6
  • <relative-size>
    • definition of, 3.6
  • sans-serif, definition of, #
  • serif, definition of, #
  • src, 4.3
  • system fonts, 3.8
  • unicameral
    • definition of, 3.5
  • unicode-range, 4.5
  • <urange>
    • definition of, 4.5

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
font | [ [ <‘font-style’> || <‘font-variant’> || <‘font-weight’> ]? <‘font-size’> [ / <‘line-height’> ]? <‘font-family’> ] | caption | icon | menu | message-box | small-caption | status-bar | inherit | see individual properties | all elements | yes | see individual properties | visual
font-family | [[ <family-name> | <generic-family> ] [, <family-name>| <generic-family>]* ] | inherit | depends on user agent | all elements | yes | N/A | visual
font-size | <absolute-size> | <relative-size> | <length> | <percentage> | inherit | medium | all elements | yes | refer to parent element's font size | visual
font-size-adjust | <number> | none | inherit | none | all elements | yes | N/A | visual
font-stretch | normal | wider | narrower | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | inherit | normal | all elements | yes | N/A | visual
font-style | normal | italic | oblique | inherit | normal | all elements | yes | N/A | visual
font-variant | normal | small-caps | inherit | normal | all elements | yes | N/A | visual
font-weight | normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit | normal | all elements | yes | N/A | visual


CSS3 Generated and Replaced Content Module

W3C Working Draft 14 May 2003

This version:
http://www.w3.org/TR/2003/WD-css3-content-20030514
Latest version:
http://www.w3.org/TR/css3-content
Previous version:
http://www.w3.org/TR/1998/REC-CSS2-19980512/generate.html
Editors:
Ian Hickson, ian@hixie.ch

Copyright © 2003 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.

Abstract

This CSS3 Module describes how to insert and move content around a document, in order to create footnotes, endnotes, section notes. Inserted content can also introduce counters and strings, which can be used for running headers and footers, section numbering, and lists. Finally, techniques for declaring replaced images, as well as scaling and cropping them using CSS, are described.

Status of this document

This is a working draft of a CSS level 3 module. It aspires to eventually become a CSS3 Recommendation.

This document is written in the context of the CSS working group which is part of the style activity (see summary).

Comments on, and discussions of this draft can be sent on the (archived) public mailing list www-style@w3.org (see instructions). W3C Members can also send comments directly to the CSS working group.

This is a working draft and may therefore be updated, replaced or rendered obsolete by other W3C documents at any time. It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress". Its publication does not imply endorsement by the W3C membership or the CSS Working Group (members only).

Patent disclosures relevant to CSS may be found on the Working Group's public patent disclosure page.

To find the latest version of this working draft, please follow the "Latest version" link above, or visit the list of W3C Technical Reports.

This document may be available in translations in the future. The English version of this specification is the only normative version.

Candidate Recommendation Exit Criteria

For this specification to exit the CR stage, the following conditions must be met:

  1. There must be at least two interoperable implementations implementing all the features. For the purposes of this criterion, we define the following terms:

    feature

    a section, subsection, assertion, or other testable aspect of the specification.

    interoperable

    passing the respective test case(s) in the test suite, or, if the implementation is not a web browser, an equivalent test. Every relevant test in the test suite should have an equivalent test created if such a UA is to be used to claim interoperability. In addition if such a UA is to be used to claim interoperability, then there must one or more additional UAs which can also pass those equivalent tests in the same way for the purpose of interoperability. The equivalent tests must be made publicly available for the purposes of peer review.

    implementation

    a user agent which:

    1. implements the feature.
    2. is available (i.e. publicly downloadable or available through some other public point of sale mechanism). This is the "show me" requirement.
    3. is shipping (i.e. development, private or unofficial versions are insufficient).
    4. is not experimental (i.e. is intended for a wide audience and could be used on a daily basis).

  2. A minimum of six months of the CR period must have elapsed. This is to ensure that enough time is given for any remaining major errors to be caught.

  3. Features will be dropped if two or more interoperable implementations are not found by the end of the CR period.

  4. Features will also be dropped if sufficient and adequate tests (by judgment of the working group) have not been produced for those features by the end of the CR period.

Table of contents

  • Status of this document
    • Candidate Recommendation Exit Criteria
  • 1. Dependencies on other modules
  • 2. Introduction
    • 2.1. Conformance Requirements
  • 3. Terminology
  • 4. Pseudo-elements
    • 4.1. Syntax
    • 4.2. Inserting content into an element: the '::before' and '::after' pseudo-elements
      • 4.2.1. Nesting '::before' and '::after' pseudo-elements
      • 4.2.2. Inserting multiple '::before' and '::after' pseudo-elements
    • 4.3. Wrapping elements in pseudo-elements with '::outside'
      • 4.3.1. Mixing '::outside' with '::before' and '::after'
    • 4.4. Inserting new content later in the document tree with '::alternate'
      • 4.4.1. Mixing '::alternate' with '::outside', '::before', and '::after'
    • 4.5. Block markers: The '::marker' pseudo-element
    • 4.6. Line markers: The '::line-marker' pseudo-element
  • 5. Moving content to later in the document: the 'move-to' property
  • 6. The 'display' property
  • 7. Specifying quotes with the 'quotes' property
    • 7.1. Inserting quotes with the 'content' property
  • 8. Automatic counters and numbering: the 'counter-increment' and 'counter-reset' properties
    • 8.1. Nested counters and scope
    • 8.2. Counter styles
    • 8.3. Counters in elements with 'display: none'
    • 8.4. Reserved Counter Names
  • 9. Named strings
  • 10. '@counter' and '@string'
    • 10.1. '@counter'
    • 10.2. '@string'
    • 10.3. Determining which counter or string-set value to use: the 'page-policy' property
  • 11. Inserting and replacing content with the 'content' property
  • 12. Replaced content
    • 12.1. The 'crop' property
    • 12.2. Intrinsic dimensions
  • 13. Examples
    • 13.1. Footnote elements
    • 13.2. Footnote attributes
    • 13.3. Styling footnotes
    • 13.4. Multiple styles on one element
    • 13.5. Section notes
    • 13.6. Top floats
  • 14. Test suite
  • 15. Profiles
  • Acknowledgments
  • References
    • Normative references
    • Other references
  • Index
  • Property index

1. Dependencies on other modules

This CSS3 module depends on the following other CSS3 modules:

  • CSS3 module: syntax [CSS3SYN]
  • CSS3 module: values and units [CSS3VAL]
  • CSS3 module: selectors [SELECT]
  • CSS3 module: lists [CSS3LIST]
  • CSS3 module: block box model [CSS3BOX]
  • CSS3 module: inline box model [CSS3LINE]
  • CSS3 module: paged media [CSS3PAGE]

2. Introduction

In some cases, authors may want user agents to render content that does not come from the document tree. One familiar example of this is a numbered list; the author does not want to mark the numbers up explicitly, he or she wants the user agent to generate them automatically. Counters and markers are used to achieve these effects.

ol { counter-reset: item; }
li { display: list-item; counter-increment: item; }
li::marker { content: counter(item, decimal) '.'; }

A simpler way to write this is:

li { display: list-item; list-style: decimal; }

Similarly, authors may want the user agent to insert the word "Figure" before the caption of a figure, or "Chapter 7" on a line before the seventh chapter title.

figure > caption::before { content: "Figure: "; }
chapter:nth-child(7) > title::before { content: "Chapter 7\A"; }

The last example could also be written in a more generic way using counters:

chapter { counter-increment: chapter; }
chapter > title::before { content: "Chapter " counter(chapter) "\A"; }

Another common effect is replacing elements with images or other multimedia content. Since not all user agents support all multimedia formats, fallbacks may have to be provided.

/* Replace <logo> elements with the site's logo, using a format
 * supported by the UA */
logo { content: url(logo.mov), url(logo.mng), url(logo.png), none; }

/* Replace <figure> elements with the referenced document, or,
 * failing that, with either the contents of the alt attribute or the
 * contents of the element itself if there is no alt attribute */
figure[alt] { content: attr(href, url), attr(alt); }
figure:not([alt]) { content: attr(href, url), contents; }

Authors may also wish to move content to a later position in a document, for instance placing images at the bottom (or top) of the page.

img { move-to: page-top; } /* move images to page-top */
@page { padding-top: 10em; } /* leave a gap at the top of the page */
body:after { /* place a box at the top of each page */
  position: fixed; top: 0; left: 0; right: 0; height: 10em;
  content: pending(page-top); /* insert the images moved to page-top */
}

In some cases, content may be inserted, alternate content moved to a later place in the flow, and a list marker inserted next to this alternate content. For example, footnotes or endnotes.

a[href]::after {
  counter-increment: footnote-number;
  content: counter(footnote-number, footnotes);
}
a[href]::after::alternate {
  display: list-item;
  content: attr(href);
  move-to: footnotes;
}
a[href]::after::alternate::marker {
  content: counter(footnote-number, footnotes);
}
@page {
  counter-reset: footnote-number;
  @footnote {
    content: pending(footnotes);
  }
}

Using initial values, the last example can also be written as:

a[href]::after { content: footnote; }
a[href]::after::alternate { content: attr(href); }

For simpler cases, e.g. where an element is simply to be used as an endnote directly, only a single declaration is required.

p.note { content: endnote; }

The initial values of the other properties are set up so that the result is as expected.

Another effect commonly requested by authors is that of line numbering. This module introduces the '::line-marker' pseudo-element that is attached to the front of every line box, which can be used for this purpose.

pre { counter-reset: line; }
pre::line-marker { counter-increment: line; content: counter(line) "."; }

This pseudo-element can also be used to simulate the indentation style found in e-mail communication:

blockquote { margin: 0; padding: 0 0 0 2em; }
blockquote > blockquote { margin-left: -1em; }
blockquote::line-marker { width: 2em; text-align: left; content: ">"; }

Generated content based on the cite and datetime attributes can create introductions or citations on the fly as well.

2.1. Conformance Requirements

Finally, in this document, requirements are expressed using the key words "MUST", "MUST NOT", "REQUIRED", "SHALL" and "SHALL NOT". Recommendations are expressed using the key words "SHOULD", "SHOULD NOT" and "RECOMMENDED". "MAY" and "OPTIONAL" are used to indicate optional features or behavior. These keywords are used in accordance with [RFC2119]. For legibility these keywords are used in lowercase form.

3. Terminology

This module introduces several pseudo-elements and allows them to nest in certain predefined ways. In order to explain the relationships between these nested pseudo-elements, three new terms have been coined.

superior parent
A pseudo-element's superior parent is the element or pseudo-element to which it is associated. e.g. the superior parent of the pseudo-element matched by '::before::after' is the pseudo-element matched by '::before', and that pseudo-element's superior parent is the element itself. The suporior parent of an '::outside(n)' pseudo-element is the '::outside(n-1)' pseudo-element. Note that an element never has a superior parent, and a pseudo-element always has exactly one.
superior siblings
The '::before' or '::after' pseudo-elements that have lower numeric arguments. e.g. '::before(2)' is a superior sibling of '::before(5)'. Only '::before' and '::after' pseudo-elements with numeric arguments greater than 1 have superior siblings.
superior
Any element or pseudo-element that is either a superior parent or superior sibling.

These terms are horrible, but they were the only ones I could think of that didn't confusingly clash with DOM terminology. Example of the horridness of the terms: the superior parent of an '::outside' pseudo-element is its rendering tree child, whose rendering hree sibling '::before' has the '::outside' pseudo-element as its superior parent.

We need a term which means "element or pseudo-element".

4. Pseudo-elements

At the heart of generated content lies pseudo-elements. Pseudo-elements create abstractions about the document tree beyond those specified by the document language. For instance, document languages do not offer mechanisms to access the first letter or first line of an element's content. CSS pseudo-elements allow style sheet designers to refer to this otherwise inaccessible information. Pseudo-elements also provide style sheet designers a way to assign style to content that does not exist in the source document.

4.1. Syntax

Certain combinations of multiple pseudo-elements per selector are allowed. All pseudo-elements must appear in a single chain at the end of the selector, with no intervening combinators.

The pseudo-element part of the selector consists of an optional set of "structural" pseudo-elements, optionally followed by a single formatting pseudo-element.

The structural pseudo-elements are alternating sets of an '::outside' pseudo-element and one or more '::before', '::after', or '::alternate' pseudo-elements. (So basically any number of '::outside', '::before', '::after', and '::alternate' pseudo-elements, so long as no two '::outside' pseudo-elements are adjacent, as that is meaningless.)

The formatting pseudo-elements are '::first-line', '::first-letter', '::marker', '::line-marker', and '::selection'. Only one of these may occur, and if present, it must be the last pseudo-element in the chain.

The allowed order for pseudo-elements is formally described by the following pseudo-BNF grammar:

pseudo-elements := structural-pseudo-elements? formatting-pseudo-element?

structural-pseudo-elements :=
  ( '::outside'? [ '::before' | '::after' | '::alternate' ] )* '::outside'?

formatting-pseudo-element :=
  '::first-line' | '::first-letter' | '::marker' | '::line-marker' | '::selection'

The '::outside', '::before', and '::after' pseudo-elements have two forms, '::outside', '::before', and '::after' and '::outside(n)', '::before(n)', and '::after(n)', where n is an integer. If the parameter part is omitted then '1' is implied. For example, '::before(1)' is the same as '::before'.

For compatability with previous levels of CSS, the '::before', '::after', '::first-line' and '::first-letter' pseudo-elements do not require two colons. This does not apply to any other pseudo-element. Authors are encouraged to use the new two-colon forms.

4.2. Inserting content into an element: the '::before' and '::after' pseudo-elements

The '::before' and '::after' pseudo-elements are used to insert content immediately before and immediately after the content of an element (or other pseudo-element). The 'content' propety is used to specify the content to insert.

For example, the following rule replaces the content of <abbr> elements with the contents of the element's title attribute:

abbr { content: attr(title); }

The following rule inserts the string "Note: " before the content of every P element whose "class" attribute has the value "note":

P.note:before { content: "Note: " }

The formatting objects (e.g., boxes) generated by an element include generated content. So, for example, changing the above style sheet to:

P.note:before { content: "Note: " }
P.note        { border: solid green }

...would cause a solid green border to be rendered around the entire paragraph, including the initial string.

Typically, the '::before' and '::after' pseudo-elements inherit any inheritable properties from the element in the document tree to which they are attached. In the general case, they inherit their properties from their superior parent.

For a '::before' or '::after' pseudo-element to be generated, all of the elements and pseudo-elements leading to it must be generated, and the pseudo-element must not have its 'content' property set to 'inhibit' or its 'display' property set to 'none'. Note that for '::before' and '::after' pseudo-elements, the initial value of 'content' computes to 'inhibit'.

Using a '::before' pseudo-element in the context of the anonymous table elements works exactly as if an actualy element had been introduced. For example:

.example::before { content: "D" }

<table>
 <tr>
  <td>A</td> <td>B</td> <td>C</td>
 </tr>
 <tr class="example">
             <td>E</td> <td>F</td>
 </tr>
</table>

An anonymous table cell box is generated around the '::before' content in this case, resulting in a 3×2 table.

4.2.1. Nesting '::before' and '::after' pseudo-elements

The selector '::before::before' represents a pseudo-element contained at the start of a pseudo-element contained at the start of an element.

For example, the following rules:

div { content: 'A' }
div::before { content: 'B'; }
div::before::before { content: 'C'; }

...would result in the following rendering objects:

,-----------------------.
| ,---------.           |
| | ,---.   |           |
| | | C | B | A         |
| | `---'   |           |
| `---------'           |
`-----------------------'

4.2.2. Inserting multiple '::before' and '::after' pseudo-elements

In contrast with the previous section, the selector '::before(2)' represents a pseudo-element before another, both of which are contained at the start of an element.

For example, the following rules:

div { content: 'A' }
div::before { content: 'B'; }
div::before(2) { content: 'C'; }

...would result in the following rendering objects:

,-----------------------.
| ,---. ,---.           |
| | C | | B | A         |
| `---' `---'           |
`-----------------------'

The '::before' selector is exactly equivalent to '::before(1)'.

A pseudo-element only exists if all the elements and pseudo-elements leading up to it exist. For instance, in the following example, only one pseudo-element is generated, the first one:

div { content: 'A' }
div::before { content: 'B'; }
div::before(2) { content: inhibit; }
div::before(3) { content: 'C'; }

It would result in the following rendering objects:

,-----------------------.
| ,---.                 |
| | B | A               |
| `---'                 |
`-----------------------'

4.3. Wrapping elements in pseudo-elements with '::outside'

An '::outside' pseudo-element is one that is generated immediately outside the pseudo-element's superior.

When given a parameter, '::outside(n)' represents an nth pseudo-element generated immediately around the n-1th pseudo-element.

For example, the following rules:

div { display: block; border: dashed; }
div::outside { display: block; border: dashed; }
div::outside(2) { display: block; border: dashed; }

...would result in the following rendering objects:

,-----------------------.   <-- border of ::outside(2)
| ,-------------------. |   <-- border of ::outside
| | ,---------------. | |   <-- border of DIV
| | | DIV           | | |
| | `---------------' | |
| `-------------------' |
`-----------------------'

A similar result would be achieved by using three nested DIV elements (except of course that would require changing the document source, which is not always possible).

One difference between using elements and using pseudo-elements is that the pseudo-elements inherit from the elements (or pseudo-elements) that generate them, not from those they are contained within.

For example, if we assume the following rules:

   div { display: block; border: green solid; }
   div::outside(1) { display: block; border: inherit; }
   div::outside(2) { display: block; border: red solid; }

...then the outermost border (from the '::outside(2)') will be red, but the middle border (from '::outside(1)') will be the same colour as the inner most border (from the element itself), namely green.

For an '::outside' pseudo-element to be generated, all of the elements and pseudo-elements leading to it must be generated, and the pseudo-element itself must not have its 'display' property set to 'none'. Note that the initial value of 'display' computes to 'none' on '::outside' pseudo-elements.

It is possible to float an element and then give it an '::outside' pseudo-element, in which case the pseudo-element is in-flow, not floated.

For example:

  p { float: right; color: green; }
  p::outside { display: inline; border: solid; }

...results in an empty inline element with a solid green border being placed in the flow at the point where the float is taken out of flow.

When an element is moved with the 'move-to' property, however, '::outside' pseudo-elements are moved too.

The 'content' property does not apply to '::outside' pseudo-elements.

4.3.1. Mixing '::outside' with '::before' and '::after'

An '::outside' pseudo-element can have any number of '::before' or '::after' pseudo-elements of its own. They are inserted before and after the '::outside' pseudo-element's contents (the element or pseudo-element that generated the '::outside' pseudo-element).

For example, the following rules:

span                     { content: "span"; }
span::before             { content: "B";    }
span::outside(1)         { display: inline; }
span::outside(1)::before { content: "A";    }
span::outside(2)         { display: inline; }
span::outside(2)::after  { content: "C";    }

...would result in the following rendering objects (including construction lines for clarity):

,--------------------------------.   <-- border of ::outside(2)
| ,----------------------.       |   <-- border of ::outside(1)
| | ,---. ,-+---+------. | ,---. |   <-- border of span, ::before,
| | | A | | | B | span | | | C | |          and ::after boxes
| | `---' `-+---+------' | `---' |
| `----------------------'       |
`--------------------------------'

This can be used to leave markers in the flow, as in:

  note { float: right; }
  note::outside { display: inline; }
  note::outside::before { content: " (see sidebar) "; }

Care must be taken when styling cases like this. If the note element was given a smaller 'font-size' or a different 'color', then, by default, the generated in-flow text would end up inheriting it.

4.4. Inserting new content later in the document tree with '::alternate'

This pseudo-element is created by setting its 'move-to' property to an identifier. It is rendered at the next occurrence of 'pending()' in a 'content' property.

In other respects it is just like a normal pseudo-element.

Note that '::alternate' pseudo-elements inherit from their associated pseudo-element or element, not from the element in which they are inserted. (The same applies to any content moved using 'move-to'). This is discussed in the section on the 'pending()' value

For an '::alternate' pseudo-element to be generated, all of the elements and pseudo-elements leading to it must be generated, and the pseudo-element must not have its 'display' property set to 'none', its 'content' property set to 'inhibit', or its 'move-to' property set to 'here'. Note that on '::alternate' pseudo-elements the initial value of 'move-to' is 'here' and the initial value of 'content' is 'inhibit'.

4.4.1. Mixing '::alternate' with '::outside', '::before', and '::after'

An '::alternate' pseudo-element can have any number of '::outside', '::before', or '::after' pseudo-elements of its own, and each of these four structural pseudo elements can have an '::alternate' pseudo-element of its own.

For example, the following rules:

span                     { content: "span"; color: green; }
span::alternate          { content: "alternate1"; move-to: example1; }
span::alternate::before  { content: "before1"; }
span::after              { content: "after1" pending(example1); color: navy; }
span::after::alternate   { content: "alternate2"; move-to: example2; }
span::after(2)           { content: "after2" pending(example2); color: purple; }

...would result in the following rendering objects (including construction lines for clarity):

,----------------------------------------------------------------------.
|      ,-----------------------------------.                           |
|      |        ,------------------------. | ,-----------------------. |
|      |        | ,---------.            | | |        ,------------, | |
| span | after1 | | before1 | alternate1 | | | after2 | alternate2 | | |
|      |        | `---------'            | | |        `------------' | |
|      |        `------------------------' | '-----------------------' |
|      `-----------------------------------'                           |
`----------------------------------------------------------------------'

4.5. Block markers: The '::marker' pseudo-element

For a '::marker' pseudo-element to be generated, its superior parent must have a computed 'display' value of 'list-item'.

For further details on the rendering model for list markers, see the CSS3 Lists module.

4.6. Line markers: The '::line-marker' pseudo-element

The '::line-marker' pseudo-element is positioned in exactly the same way as the '::marker' pseudo-element, but appears on every line, not just the first.

Line boxes are responsible for generating '::line-marker' pseudo-elements. For each line, one such marker is created for every block ancestor in the current formatting context. (Formatting contexts are created by the root element, floats, positioned content, cells, and inline-blocks. See the CSS3 Box Model module for more information. [CSS3BOX]) In addition, the '::line-marker' pseudo-element itself must have a 'content' property that has a computed value other than 'none' or 'inhibit'.

5. Moving content to later in the document: the 'move-to' property

Name: | move-to
Value: | normal | here | <identifier>
Initial: | normal
Applies To: | all elements, ::before, ::after, and ::alternate
Inherited: | no
Percentages: | N/A
Media: | all
Computed value: | The specified value unless that is 'normal', as per the prose below.

The 'move-to' property causes the element or pseudo-element to be removed from the flow and reinserted at a later point in the document. The content is reinserted using the 'pending()' value of the 'content' property.

This property applies to all elements as well as the '::before', '::after', and '::alternate' pseudo-elements. The '::alternate' pseudo-element in fact exists exclusively for the purpose of being moved by this property, e.g. in the creation of footnotes.

normal

For '::alternate' pseudo-elements, if the superior parent uses the 'footnote' counter in its 'content' property then the computed value of 'move-to' is 'footnotes'.

For '::alternate' pseudo-elements, if the superior parent uses the 'endnote' counter in its 'content' property then the computed value of 'move-to' is 'endnotes'.

For '::alternate' pseudo-elements, if the superior parent uses the 'section-note' counter in its 'content' property then the computed value of 'move-to' is 'section-notes'.

Otherwise the computed value of the move-to property is 'here'.

here
The element or pseudo-element is not moved. This value inhibits the creation of '::alternate' pseudo-elements and any pseudo-elements that have such a pseudo-element as a superior.
<identifier>
The element is not displayed at the current location, but at the next occurrence of 'pending(<identifier>)' (where the identifiers match), with all other elements moved to that point, in document order. If at the end af the document (after the '::after' pseudo-elements of the root element) there are outstanding elements, then they are all inserted in document order at that point.

Note that elements and pseudo-elements that have been moved using 'move-to' still inherit from their associated pseudo-element or element, and not from the element in which they are inserted. This is discussed in the section on the 'pending()'. value

6. The 'display' property

Name: | display
New values: | normal
Initial: | normal
Applies To: | all elements, ::before, ::after, ::alternate, and ::outside
Inherited: | no
Percentages: | N/A
Media: | all
Computed value: | The specified value unless that is 'normal', as described below.

Note: all values apply to the four pseudo-elements listed. Thus you can create entire tables, insert rubies, or generate other complex layouts using only generated content. This differs from CSS2 which only allowed a limited subset of values to apply to each pseudo-element.

normal

For elements, '::before', and '::after', computes to 'inline'.

For '::alternate': if the superior parent's 'content' property uses the 'footnote', 'endnote', or 'section-note' property then it computes to 'list-item', otherwise it computes to 'block'. Note that if the 'move-to' property doesn't compute to an identifier then the '::alternate' pseudo-element isn't generated in the first place and therefore the value of 'display' is not relevant. In those cases, 'normal' still computes as described above but the result does not affect layout.

For '::outside', computes to 'none'. This prevents the generation of the pseudo-element, but does not stop the pseudo-element's superior parent from being generated (as it would if the '::outside' pseudo-element was replaced by a real element in an attempt to produce the same layout).

none

On elements, this inhibits the element, including any children and any pseudo-elements which have this element as a superior parent, from being rendered, anywhere.

On pseudo-elements, this inhibits the creation of the element and furthermore prevents the creation of any pseudo-elements which have this pseudo-element as a superior.

list-item

To declare a list item, the 'display' property should be set to 'list-item'. This, in addition to generating a '::marker' pseudo-element and enabling the properties described in the Lists module, causes that element to increment the list item counter 'list-item'. (This does not affect the specified or computed values of the counter properties.)

The 'list-item' counter is a real counter, and can be directly affected using the 'counter-increment' and 'counter-reset' properties. It can also be used in the 'counter()' and 'counters()' function forms.

The CSS3 box module may define other 'display' values which generate a list marker. These should also affect the 'list-item' counter.

POWERED BY HeroNote

Note that the new list marker model makes the 'marker' display type redundant. That display type is therefore obsolete in the CSS3 Lists model.

Note that while this property doesn't apply to '::marker' pseudo-elements, they only get generated if thir superior parent has a computed 'display' value of 'list-item', and they are always rendered as if they had an 'inline-block' display type.

Similarly, while this property applies to '::before', '::after', '::alternate', '::outside' those pseudo-elements only get generated if they have no superiors with computed values of 'display' that are 'none' or superiors with computed values of 'content' that are 'inhibit'.

7. Specifying quotes with the 'quotes' property

Name: | quotes
Value: | foo | bar
Initial: | text
Applies To: | all elements, ::before, ::after, ::alternate, ::marker, ::line-marker, margin areas, and @footnote areas
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified value

This property specifies quotation marks for any number of embedded quotations. Values have the following meanings:

none
The 'open-quote' and 'close-quote' values of the 'content' property produce no quotations marks, as if they were 'no-open-quote' and 'no-close-quote' respectively.
[ <string> <string> ]+
Values for the 'open-quote' and 'close-quote' values of the 'content' property are taken from this list of pairs of quotation marks (opening and closing). The first (leftmost) pair represents the outermost level of quotation, the second pair the first level of embedding, etc. The user agent must apply the appropriate pair of quotation marks according to the level of embedding.

For example, applying the following style sheet:

/* Specify pairs of quotes for two levels in two languages */
:lang(en) > q { quotes: '"' '"' "'" "'" }
:lang(no) > q { quotes: "+" ";" "<" ">" }

/* Insert quotes before and after Q element content */
q::before { content: open-quote }
q::after  { content: close-quote }

to the following HTML fragment:

<HTML lang="en">
  <HEAD>
    <TITLE>Quotes</TITLE>
  </HEAD>
  <BODY>
    <P><Q>Quote me!</Q>
  </BODY>
</HTML>

would allow a user agent to produce:

"Quote me!"

while this HTML fragment:

<HTML lang="no">
  <HEAD>
    <TITLE>Quotes</TITLE>
  </HEAD>
  <BODY>
    <P><Q>Trøndere gråter når <Q>Vinsjan på kaia</Q> blir deklamert.</Q>
  </BODY>
</HTML>

would produce:

+Trøndere gråter når <Vinsjan på kaia> blir deklamert.;

Note. While the quotation marks specified by 'quotes' in the previous examples are conveniently located on computer keyboards, high quality typesetting would require different ISO 10646 characters. The following informative table lists some of the ISO 10646 quotation mark characters:

Codepoint |  | Description
" | U+0022 | QUOTATION MARK (the ASCII double quotation mark)
' | U+0027 | APOSTROPHE (the ASCII single quotation mark)
< | U+2039 | SINGLE LEFT-POINTING ANGLE QUOTATION MARK
> | U+203A | SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
« | U+00AB | LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
» | U+00BB | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
' | U+2018 | LEFT SINGLE QUOTATION MARK (single high-6)
' | U+2019 | RIGHT SINGLE QUOTATION MARK (single high-9)
" | U+201C | LEFT DOUBLE QUOTATION MARK (double high-6)
" | U+201D | RIGHT DOUBLE QUOTATION MARK (double high-9)
" | U+201E | DOUBLE LOW-9 QUOTATION MARK (double low-9)

7.1. Inserting quotes with the 'content' property

Quotation marks are inserted in appropriate places in a document with the 'open-quote' and 'close-quote' values of the 'content' property. Each occurrence of 'open-quote' or 'close-quote' is replaced by one of the strings from the value of 'quotes', based on the depth of nesting.

'Open-quote' refers to the first of a pair of quotes, 'close-quote' refers to the second. Which pair of quotes is used depends on the nesting level of quotes: the number of occurrences of 'open-quote' in all generated text before the current occurrence, minus the number of occurrences of 'close-quote'. If the depth is 0, the first pair is used, if the depth is 1, the second pair is used, etc. If the depth is greater than the number of pairs, the last pair is repeated.

Note that this quoting depth is independent of the nesting of the source document or the formatting structure.

Some typographic styles require open quotation marks to be repeated before every paragraph of a quote spanning several paragraphs, but only the last paragraph ends with a closing quotation mark. In CSS, this can be achieved by inserting "phantom" closing quotes. The keyword 'no-close-quote' decrements the quoting level, but does not insert a quotation mark.

The following style sheet puts opening quotation marks on every paragraph in a BLOCKQUOTE, and inserts a single closing quote at the end:

BLOCKQUOTE P:before     { content: open-quote }
BLOCKQUOTE P:after      { content: no-close-quote }
BLOCKQUOTE P.last:after { content: close-quote }

This relies on the last paragraph being marked with a class "last", since there are no selectors that can match the last child of an element.

For symmetry, there is also a 'no-open-quote' keyword, which inserts nothing, but increments the quotation depth by one.

Note. If a quotation is in a different language than the surrounding text, it is customary to quote the text with the quote marks of the language of the surrounding text, not the language of the quotation itself.

For example, French inside English:

The device of the order of the garter is "Honi soit qui mal y pense."

English inside French:

Il disait: + Il faut mettre l'action en < fast forward >.;

A style sheet like the following will set the 'quotes' property so that 'open-quote' and 'close-quote' will work correctly on all elements. These rules are for documents that contain only English, French, or both. One rule is needed for every additional language. Note the use of the child combinator (">") to set quotes on elements based on the language of the surrounding text:

:lang(fr) > * { quotes: "+" ";" "\2039" "\203A" }
:lang(en) > * { quotes: "\201C" "\201D" "\2018" "\2019" }

The quotation marks for English are shown here in a form that most people will be able to type. If you can type them directly, they will look like this:

:lang(fr) > * { quotes: "+" ";" "<" ">" }
:lang(en) > * { quotes: """ """ "'" "'" }

8. Automatic counters and numbering: the 'counter-increment' and 'counter-reset' properties

Automatic numbering in CSS2 is controlled with two properties, 'counter-increment' and 'counter-reset'. The counters defined by these properties are used with the 'counter()' and 'counters()' functions of the the 'content' property.

Name: | counter-increment
Value: | [ <identifier> <integer>? ]+ | none
Initial: | note
Applies To: | all elements, ::before, ::after, ::alternate, ::marker, ::line-marker, margin areas, @footnote areas, and @page context
Inherited: | no
Percentages: | N/A
Media: | alll
Computed value: | specified value
Name: | counter-reset
Value: | [ <identifier> <integer>? ]+ | none
Initial: | note
Applies To: | all elements, ::before, ::after, ::alternate, ::marker, ::line-marker, margin areas, @footnote areas, and @page context
Inherited: | no
Percentages: | N/A
Media: | alll
Computed value: | specified value

The 'counter-increment' property accepts one or more names of counters (identifiers), each one optionally followed by an integer. The integer indicates by how much the counter is incremented for every occurrence of the element. The default increment is 1. Zero and negative integers are allowed.

The 'counter-reset' property also contains a list of one or more names of counters, each one optionally followed by an integer. The integer gives the value that the counter is set to on each occurrence of the element. The default is 0.

If 'counter-increment' refers to a counter that is not in the scope (see below) of any 'counter-reset', the counter is assumed to have been reset to 0 by the root element.

This example shows a way to number chapters and sections with "Chapter 1", "1.1", "1.2", etc.

H1:before {
    content: "Chapter " counter(chapter) ". ";
    counter-increment: chapter;  /* Add 1 to chapter */
    counter-reset: section;      /* Set section to 0 */
}
H2:before {
    content: counter(chapter) "." counter(section) " ";
    counter-increment: section;
}

If an element or pseudo-element resets or increments a counter and also uses it (in its 'content' property), the counter is used after being reset or incremented.

If an element or pseudo-element both resets and increments a counter, the counter is reset first and then incremented.

The 'counter-reset' property follows the cascading rules. Thus, due to cascading, the following style sheet:

H1 { counter-reset: section -1 }
H1 { counter-reset: imagenum 99 }

will only reset 'imagenum'. To reset both counters, they have to be specified together:

H1 { counter-reset: section -1 imagenum 99 }

8.1. Nested counters and scope

Counters are "self-nesting", in the sense that re-using a counter in a child element automatically creates a new instance of the counter. This is important for situations like lists in HTML, where elements can be nested inside themselves to arbitrary depth. It would be impossible to define uniquely named counters for each level.

Thus, the following suffices to number nested list items. The result is very similar to that of setting 'display:list-item' and 'list-style: inside' on the LI element:

OL { counter-reset: item }
LI { display: block }
LI:before { content: counter(item) ". "; counter-increment: item }

The self-nesting is based on the principle that every element or pseudo-element that has a 'counter-reset' for a counter X, creates a fresh counter X, the scope of which is the element or pseudo-element, its following siblings, and all the descendants of the element or pseudo-element and its following siblings.

In the example above, an OL will create a counter, and all children of the OL will refer to that counter.

If we denote by item[n] the nth instance of the "item" counter, and by "(" and ")" the beginning and end of a scope, then the following HTML fragment will use the indicated counters. (We assume the style sheet as given in the example above).

<OL>               <!-- (set item[0] to 0          -->
  <LI>item         <!--  increment item[0] (= 1)   -->
  <LI>item         <!--  increment item[0] (= 2)   -->
    <OL>           <!--  (set item[1] to 0         -->
      <LI>item     <!--   increment item[1] (= 1)  -->
      <LI>item     <!--   increment item[1] (= 2)  -->
      <LI>item     <!--   increment item[1] (= 3)  -->
        <OL>       <!--   (set item[2] to 0        -->
          <LI>item <!--    increment item[2] (= 1) -->
        </OL>      <!--   )                        -->
        <OL>       <!--   (set item[3] to 0        -->
          <LI>     <!--    increment item[3] (= 1) -->
        </OL>      <!--   )                        -->
      <LI>item     <!--  increment item[0] (= 3)   -->
  <LI>item         <!--  increment item[0] (= 4)   -->
</OL>              <!-- )                          -->
<OL>               <!-- (reset item[4] to 0        -->
  <LI>item         <!--  increment item[4] (= 1)   -->
  <LI>item         <!--  increment item[4] (= 2)   -->
</OL>              <!-- )                          -->

The 'counters()' function generates a string composed of the values of all counters with the same name, separated by a given string.

The following style sheet numbers nested list items as "1", "1.1", "1.1.1", etc.

OL { counter-reset: item }
LI { display: block }
LI:before { content: counters(item, "."); counter-increment: item }

8.2. Counter styles

By default, counters are formatted with decimal numbers, but all the styles available for the 'list-style-type' property are also available for counters. The notation is:

counter(name)

for the default style, or:

counter(name, <'list-style-type'>)

All the styles are allowed, including the glyph types such as 'disc', 'circle', and 'square'. The 'none' value is also allowed, and causes the counter to generate nothing.

H1:before        { content: counter(chno, upper-latin) ". " }
H2:before        { content: counter(section, upper-roman) " - " }
BLOCKQUOTE:after { content: " [" counter(bq, hebrew) "]" }
DIV.note:before  { content: counter(notecntr, disc) " " }
P:before         { content: counter(p, none) } /* inserts nothing */

8.3. Counters in elements with 'display: none'

An element that is not displayed ('display' set to 'none') cannot increment or reset a counter.

For example, with the following style sheet, H2s with class "secret" do not increment 'count2'.

H2.secret {counter-increment: count2; display: none}

Elements with 'visibility' set to 'hidden', on the other hand, do increment counters.

8.4. Reserved Counter Names

The 'list-item', 'section-note', 'endnote', and 'footnote' counters are not reserved. They are ordinary counters that happen to be incremented and used by other properties as well as the counter properties.

The 'total-pages' counter, however, is reserved. Resetting or increasing this counter has no effect. See the Paged Media module [CSS3PAGE] for more information on this counter.

9. Named strings

CSS3 introduces 'named strings', which are the textual equivalent of counters and which have a distinct namespace from counters. Named strings follow the same nesting rules as counters. The 'string-set' property accepts values similar to the 'content' property, including the extraction of the current value of counters.

Named strings are a convenient way to pull metadata out of the document for insertion into headers and footers. In HTML, for example, META elements contained in the document HEAD can set the value of named strings. In conjunction with attribute selectors, this can be a powerful mechanism:

META[author] { string-set: author attr(author); }
HEAD > TITLE { string-set: title contents; }
@page:left {
  @top {
    text-align: left;
    vertical-align: middle;
    content: string(title);
  }
}
@page:right {
  @top {
    text-align: right;
    vertical-align: middle;
    content: string(author);
  }
}

This section is missing a property definition.

This section is missing a definition of the string() function.

The following example captures the contents of H1 elements, which represent chapter names in this hypothetical document.

H1 { string-set: chapter contents; }

When an H1 element is encountered, the 'chapter' string is set to the element's textual contents, and the previous value of 'chapter', if any, is overwritten.

10. '@counter' and '@string'

It's possible that the page in question itself contains multiple elements that set counters or increment strings. Should the formatter use the value at the start of the page or at the end of the page? To address this question, authors may use @counter or @string declaration blocks and the 'page-policy' property, which applies only to strings and counters.

What about counter-policy and string-policy

10.1. '@counter'

This 'list-style-type' property can be used with an '@counter' rule to change the counter's default counter style. This is typicially used to change, for example, the footnote style:

@counter footnote {
   list-style-type: super-decimal;
}

The default list style types for counters is 'decimal' except for the 'footnote' counter which defaults to 'footnotes'.

Syntax still to come.

10.2. '@string'

Syntax still to come.

10.3. Determining which counter or string-set value to use: the 'page-policy' property

Name: | page-policy
Value: | start | first | last
Initial: | start
Applies to: | @counter and @string blocks
Inherited: | N/A
Percentages: | N/A
Media: | paged
Computed value: | specified value

'page-policy' determines which page-based occurance of a given element is applied to a counter or string value:

start
Takes the value of the counter or string at the beginning of the page (before applying style to the elements of the page, but after applying it to the @page context itself).
first
Takes the value after the first state change in the counter or string during processing of the page.
last
Takes the value following the final state change on the page.

The following example places the chapter name in the header, specifying that it is the value of the string at the end of the page. Example:

@string chapter { page-policy: last; }
@page {
  size: 21.0cm 29.7cm; /* A4 */
  @top {
    text-align: right;
    vertical-align: center;
    content: string (chapter);
  }
}

To use the chapter name as it was when the processing of the page started, the designer would specify a 'page-policy' of 'start' instead of 'last'. Designers can also use the value of a string or counter after its first state change on a page by specifying 'first'.

11. Inserting and replacing content with the 'content' property

Name: | content
Value: | [ <uri> ',' ]* [ normal | none | inhibit | <content-list> ]
Initial: | normal
Applies To: | all elements, ::before, ::after, ::alternate, ::marker, ::line-marker, margin areas, and @footnote areas
Inherited: | no
Percentages: | N/A
Media: | all
Computed value: | The specified value with each occurrence of 'normal' expanded as per the prose below.

The 'content' property dictates what is rendered inside the element or pseudo-element. It takes a comma separated list of URIs followed by a space separated list of tokens. If there are multiple URIs provided, then each is tried in turn until a value which is both available and supported is found. The last value is used as a fallback if the others fail.

<uri>

If the value is the only value in the list, as the two URIs in the example below are:

h1 { content: url(header/mng), url(header/png); }

...then if the URI is available and the format is supported, then the element or pseudo-element becomes a replaced element, otherwise, the next item in the comma separated list is used, if any. In the example above, if 'header/mng' wasn't in a supported format, then 'header/png' would have been used instead. If no alternatives exist, then 'none' is used as a final fallback, so in the example above, if 'header/png' wasn't available either, then the <h1> element would be empty.

Thus to make an element fallback on its contents, you have to explicitly give 'contents' as a fallback:

content: url(1), url(2), url(3), contents;

If the URI is not the only value in the list, as the second URI in the following example:

h1 { content: url(welcome), "Welcome to: " url(logo); }

...then if the file is available and the format is supported, then an anonymous replaced inline element is inserted, otherwise the image is ignored (as if it hadn't been given at all).

When a URI is used as replaced content, it affects the generation of '::before' and '::after' pseudo-elements.

normal

For an element, this computes to 'contents'.

For '::alternate', if the superior parent uses the 'footnote', 'endnote', or 'section-note' counter in its 'content' property then the computed value of 'content' is 'contents', otherwise it computes to 'inhibit'.

For '::before', '::after', and '::line-marker' this computes to 'inhibit'.

For '::marker', if the superior parent's superior parent uses 'footnote' in its 'content' property then 'normal' computes to the computed value of the 'list-style-image' property if the list-style-image is not 'none', otherwise 'counter(footnote, <list-style-type>) "suffix"' where <list-style-type> is the computed value of the 'list-style-type' property if that property is not 'none' and suffix is the suffix appropriate for that list style type, otherwise 'inhibit'.

For '::marker', if the superior parent's superior parent uses 'endnote' in its 'content' property then 'normal' computes to the computed value of the 'list-style-image' property if the list-style-image is not 'none', otherwise 'counter(endnote, <list-style-type>) "suffix"' where <list-style-type> is the computed value of the 'list-style-type' property if that property is not 'none' and suffix is the suffix appropriate for that list style type, otherwise 'inhibit'.

For '::marker', if the superior parent's superior parent uses 'section-note' in its 'content' property then 'normal' computes to the computed value of the 'list-style-image' property if the list-style-image is not 'none', otherwise 'counter(section-note, <list-style-type>) "suffix"' where <list-style-type> is the computed value of the 'list-style-type' property if that property is not 'none' and suffix is the suffix appropriate for that list style type, otherwise 'inhibit'.

Otherwise, for '::marker', if the computed value of 'display' for the superior parent is 'list-item' then 'normal' computes to the computed value of the 'list-style-image' property if the list-style-image is not 'none', otherwise 'counter(list-item, <list-style-type>) "suffix"' where <list-style-type> is the computed value of the 'list-style-type' property if that property is not 'none' and suffix is the suffix appropriate for that list style type, otherwise 'inhibit'.

For the '@footnote' area, it computes to 'pending(footnote)'.

For margin areas, it computes to 'none'.

none

On elements, this inhibits the children of the element from being rendered as children of this element, as if the element was empty.

On pseudo-elements it causes the pseudo-element to have no content.

In neither case does it prevent any pseudo-elements which have this element or pseudo-element as a superior from being generated.

inhibit

On elements, this inhibits the children of the element from being rendered as children of this element, as if the element was empty.

On pseudo-elements, this inhibits the creation of the pseudo-element, as if 'display' computed to 'none'.

In both cases, this further inhibits the creation of any pseudo-elements which have this pseudo-element as a superior.

<content-list>

[ pending(<identifier>) | <string> | contents | footnote | endnote | section-note | list-item | <counters> | <strings> | open-quote | close-quote | no-open-quote | no-close-quote | <glyph> | <uri> | <date> | document-url | <target> ]+

One or more of the following values, concatenated.

pending(<identifier>)

This causes all elements and pseudo-elements whose 'move-to' property computes to the specified identifier to be inserted as children of the current element (or pseudo-element). Note: This doesn't change the DOM, and elements and pseudo-elements that have been moved inherit from their position in the DOM, not from their new position.

This must be the case, because otherwise it would be impossible to determine the value of 'move-to'. Unfortunately, this can cause some unfortunate discontinuities, such as adjacent footnotes using different fonts because they were moved from elements with different fonts. It is therefore important that moved content be styled with the new location in mind.

Note that only elements and pseudo-element that have not yet been reinserted into content are moved. For example:

moved { move-to: insert; }
insert { content: pending(insert); }

<root>
  <moved> A </moved>
  1
  <insert/>
  2
  <moved> B </moved>
  3
  <insert/>
</root>

...would result in "1 A 2 3 B".

If used on an element or pseudo-element (particularly '::alternate') which has a 'move-to' property with a computed value other than 'here', the content pending at the pseudo-element's superior's position is inserted, not the content pending at the element or pseudo-element's insertion point. Similarly if used on a child of an element that has been moved: the 'content' property is evaluated before the element is inserted in its new position. This should prevent an element ever being inserted into itself or other such existential conundrums.

Counters on content that is moved in this way are evaluated at the point of origin, not the insertion point.

The identifiers 'here' and 'normal' are valid, in that they do not cause a parse error and are not ignored, but they are useless as the 'move-to' property cannot ever be set to an identifier with either of those values.

Need to define exactly how this interacts with 'position:fixed'. Does 'position:fixed' cause multiple rendering objects to be created, one per page? If so where does 'move-to' on a 'position:fixed' element move from?

"" (the empty string)

If the element or pseudo-element's 'display' property computes to anything but 'inline' then the element or pseude-element contains an empty anonymous inline box, otherwise the element contains an empty string.

(This is a formal way of saying that an empty string is different from 'none' in that it forces the creation of a line box, even if the line box would be empty.)

<string>

The element or pseudo-element contains the specified string. Occurrences of line-feed or space characters in the string are handled according to the properties given in the Text module.

contents

The element's descendents. Since this can only be used once per element (you can't duplicate the children if, e.g., one is a plugin or form control), it is handled as follows:

If set on the element:

Always honoured. Note that this is the default, since the initial value of 'content' is 'normal' and 'normal' computes to 'contents' on an element.

If set on a '::marker' or '::line-marker' pseudo-element:

Evaluates to nothing (like 'none').

If set on one of the element's other pseudo-elements:

Check to see that it is not set on a "previous" pseudo-element, in the following order, depth first:

  1. the element itself
  2. ::alternate
  3. ::before
  4. ::after

If it is already used, then it evaluates to nothing (like 'none'). Only pseudo-elements that are actually generated are checked. Thus

/* ::after(2) { content: inhibit; } /* implied by initial value */
::after(9999) { content: contents }

...would typically not change anything.

So for example, in the following case:

foo { content: none; }
foo::before { content: '[' counter(footnote) ']' contents; }
foo::alternate { content: counter(footnote) '. ' contents; }

...the '::before' pseudo-element's contents would become '[1]', and the footnote would contain '1. ' followed by the element's contents, because the '::alternate' takes priority over the '::before' pseudo-element at the same depth.

However, in the following case:

/* foo { content: normal; }   /* this is the initial value */
foo::after { content: contents; }

...the element's 'content' property would compute to 'contents' and the after pseudo element would have no contents (equivalent to 'none') and thus would not appear.

Note that while it is useless to include 'contents' twice in a single 'content' property, that is not a parse error. The second occurrence simply has no effect, as it has already been used. It is also not a parse error to use it on a marker pseudo-element, it is only during the rendering stage that it gets treated like 'none'.

footnote

Shorthand for 'counter(footnote, normal)'. This is intended to be used on the in-flow part of a footnote.

endnote

Shorthand for 'counter(endnote, normal)'. This is intended to be used on the in-flow part of a endnote.

section-note

Shorthand for 'counter(section-note, normal)'. This is intended to be used on the in-flow part of a section-note.

list-item

Shorthand for 'counter(list-item, normal)'. Note that this is not equivalent to 'normal' when set on a '::marker' pseudo-element that has a superior with 'display' set to 'list-item', as it ignores the 'list-style' properties.

<counters>

Counters may be specified with two different functions: 'counter()' or 'counters()'. The former has two forms: 'counter(name)' or 'counter(name, style)'. The generated text is the value of the named counter at this point in the formatting structure; it is formatted in the indicated style (the default is specified using '@counter' rules). The latter function also has two forms: 'counters(name, string)' or 'counters(name, string, style)'. The generated text is the value of all counters with the given name at this point in the formatting structure, separated by the specified string. The counters are rendered in the indicated style (the default is again specified using '@counter' rules). See the section on automatic counters and numbering for more information.

<strings>

Set strings may be specified with the 'string(name)' expression. The generated text is the value of the named string at this point in the formatting structure. See the section on named strings for more information.

open-quote and close-quote

These values are replaced by the appropriate string from the 'quotes' property.

no-open-quote and no-close-quote

Inserts nothing (as in 'none'), but increments (decrements) the level of nesting for quotes.

<glyph>

Inserts the specified symbol. The available symbols are:

box
A hollow square. (like ? U+25A1 WHITE SQUARE, ? U+25FB WHITE MEDIUM SQUARE, or ? U+25FD WHITE MEDIUM SMALL SQUARE)
check
A check mark. On interactive media, it is suggested that the same glyph which is used on the platform to render a checked menu item be used for 'check'. (like ? U+2713 CHECK MARK)
circle
A hollow circle. (like ? U+25E6 WHITE BULLET)
diamond
A filled diamond. On interactive media, it is suggested that the same glyph which is used on the platform next to a selected menu item be used for 'diamond'. On some platforms, this is similar to 'disc'. (like ? U+25C6 BLACK DIAMOND or ? U+2666 BLACK DIAMOND SUIT)
disc
A filled circle. (like . U+2022 BULLET)
hyphen
A hyphen bullet. (like ? U+2043 HYPHEN BULLET or - U+2013 EN DASH)
square
A filled square. (like ? U+25A0 BLACK SQUARE, ? U+25FC BLACK MEDIUM SQUARE, or ? U+25FE BLACK MEDIUM SMALL SQUARE)

For more information on the list of symbols and their definitions, see the Lists module [CSS3LIST].

<date>

The 'date(format)' expression returns the current date and/or time, formatted according to the specified formatting string. Formatting strings will be defined in a future version of this draft and may be based on POSIX date formatting strings.

document-url

The URI of the current document. For local files, this may simply be the local file name.

<target>

Using the target expressions, authors can write cross-references. Need to write this up.

12. Replaced content

If the computed value of the part of the 'content' property that ends up being used is a single URI, then the element or pseudo-element is a replaced element. The box model defines different rules for the layout of replaced elements than normal elements. Replaced elements do not have '::before' and '::after' pseudo-elements; the 'content' property in the case of replaced content replaces the entire contents of the element's box.

To insert text around replaced content, '::outside::before' and '::outside::after' may be used.

12.1. The 'crop' property

Name: | crop
Values: | <shape> | auto
Initial: | auto
Applies To: | replaced elements
Inherited: | no
Percentages: | relative to intrinsic size
Media: | visual
Computed value: | The specified value.

This property allows a replaced element to be just a rectangular area of an object, instead of the whole object.

The 'crop' property adds a step when determining the intrinsic dimensions of an element. With 'crop', the notion of computed intrinsic width and height are introduced. When the layout algorithms reference the "intrinsic width" (and/or height), they are referring to the computed intrinsic width and height.

The computed intrinsic width and height of an element are the result of applying the crop to the actual intrinsic width and height of the element.

'auto'
The element's computed intrinsic width and height are the same as its actual intrinsic width and height.
rect(top, right, bottom, left)
Each of the four arguments can be a <length> or a <percentage>. All percentage values are computed relative to the intrinsic dimensions of the element, if there is one. Values are offsets relative to the top left of the element. The computed intrinsic width and height of the element are determined by subtracting the left from the right for the width, and similarly top from bottom for the height. However, if this computation results in a negative value, it is considered to be zero.
inset-rect(top, right, bottom, left)
Like rect(), except that the values are offsets relative to the respective edges of the element.

If the element does not have an intrinsic width, the UA may in some cases be able to infer the intrinsic width that the style sheet writer assumed. First the UA must find the computed 'width' and computed 'height' and then the intrinsic width can be found as follows (the intrinsic height is analogous):

  1. If 'crop' is 'auto', the assumed intrinsic width is the same as the computed value of 'width'
  2. If 'crop' is 'rect(t, r, b, l)' and r is a percentage, the intrinsic width can be solved from the equation: r = computed 'width' + l
  3. If 'crop' is 'rect(t, r, b, l)' and r is not a percentage, the intrinsic width cannot be computed and the result is UA dependent.
  4. If 'crop' is 'inset-rect(t, r, b, l)', then the intrinsic width can always be solved from the equation intrinsic width = l + computed 'width' + r

Note: 'crop' does not impact the scaling, stretching, tiling or positioning of the replaced element. 'crop' simply allows the author to essentially use a part of a replaced element in place of the element itself for all intents and purposes.

The following example displays both the whole sheep and its head:

.thumbnail { crop: rect(0px, 115px, 85px, 30px) }

<p>Here is Woolly, the CSS sheep:
<img src="woolly" alt="Woolly">
<p>And here he is as a thumbnail:
<img src="woolly" class="thumbnail" alt="Woolly thumbnail">

The result might look like this:

Text with images of the whole sheep and the head of the sheep

The same image, once uncropped, once cropped.

12.2. Intrinsic dimensions

Replaced content may have intrinsic dimensions, such as: an intrinsic width and an intrinsic height, a fixed intrinsic ratio, or a ratio calculable from a specified width or height.

The 'height' and 'width' properties' 'auto' values change meaning when applied to a replaced element with intrinsic dimensions.

If applied to both dimensions, then if the replaced content has an intrinsic width, the width computes to the actual width of the content, otherwise if the replaced content has an intrinsic height, the height computes to the actual height of the content, otherwise the width is UA-defined. The remaining dimension is then calculated so as to preserve the aspect ratio. (This paragraph assumes a vertical block progression direction. In a horizontal block progression direction context, the 'height' property is done first.)

If applied to only one of the two properties only, then if the element has any intrinsic dimensions at all, the property is calculated to preserve the aspect ratio, otherwise the property is given a UA-specific value.

13. Examples

13.1. Footnote elements

To make an element into a footnote, leaving a marker behind:

fn { content: footnote; }

By carefully defining the computation rules of initial values, this causes the following:

/* Replace the element with a footnote leader counter */
fn { content: counter(footnote, footnotes); }

/* Move the content of the element into the '::alternate'
   pseudo-element, and mark that pseudo-element to be moved
   to the footnote area. */
fn::alternate { content: contents; move-to: footnotes; }

/* Make the footnote marker be the footnote counter */
fn::alternate::marker { content: counter(footnote, footnotes); }

/* Make the footnote area expect to receive footnotes. */
@footnote { content: pending(footnotes); }

Note that there is no magic involved, the computation rules are simply carefully designed to compute as described above.

13.2. Footnote attributes

To make an element's attribute into a footnote:

[href]::after { content: footnote; }
[href]::after::alternate { content: attr(href); }

13.3. Styling footnotes

To use numbers for footnotes instead of symbols:

@counter footnote {
    list-style-type: decimal-super;
}

13.4. Multiple styles on one element

To put three borders around an element:

h1 { border: solid blue; }
h1::outside(1) { border: solid green; display: block; }
h1::outside(2) { border: solid red; display: block; }

To put a background in each corner:

body::outside(1) { display: block; background: top left url(tl); }
body::outside(2) { display: block; background: top right url(tr); }
body::outside(3) { display: block; background: bottom left url(bl); }
body::outside(4) { display: block; background: bottom right url(br); }

13.5. Section notes

To use all title attributes as section numbered notes:

section > [title]::after { content: section-note; }
section > [title]::after::alternate { content: attr(title); }
section::after { content: 'Notes: ' pending(section-notes); }

Note how setting 'content' to 'section-note' on the '::after' pseudo-element automatically sets 'move-to' on the '::after::alternate' pesudo-element to 'section-notes', due to the definition of the initial value of 'move-to'.

13.6. Top floats

Top floats (assuming fixed position elements are positioned relative is the page area's border edge):

img {
  move-to: top-floats;
}
:root::before {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 10em;
  content: pending(top-floats);
}
@page {
  padding-top: 10em;
}

14. Test suite

A test suite checking many of the more involved of this specifiation, as well as the basics, will be created and used to establish whether the CR exit criteria have been met.

15. Profiles

There will be several profiles: Level 1 (equivalent to the CSS1 model), Level 2 (not quite identical to the CSS2 model), and Full.

An implementation can implement a superset of the features and claim conformance to the profile.

Acknowledgments

Stuart Ballard, David Baron, Bert Bos, and Tantek Çel&#x0131?k provided invaluable suggestions used in this specification.

References

Normative references

[CSS3BOX]
Bert Bos. CSS3 module: box model. 26 July 2001. W3C working draft. (Work in progress.) URL: http://www.w3.org/TR/2001/WD-css3-box-20010726
[CSS3LINE]
Eric A. Meyer. CSS3 module: linebox model. (forthcoming). W3C working draft. (Work in progress.)
[CSS3LIST]
Tantek Çelik; Ian Hickson. CSS3 module: lists. 20 Feb 2002. W3C working draft. (Work in progress.) URL: http://www.w3.org/TR/2002/WD-css3-lists-20020220
[CSS3PAGE]
Robert Stevahn. CSS3 module: paged media. 28 Sep 1999. W3C working draft. (Work in progress) URL: http://www.w3.org/TR/1999/WD-css3-page-19990928
[CSS3SYN]
David Baron. CSS3 module: syntax. (forthcoming). W3C working draft. (Work in progress.)
[CSS3VAL]
Håkon Wium Lie. CSS3 module: values and units. (forthcoming). W3C working draft. (Work in progress.)
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[SELECT]
Daniel Glazman; Tantek Çelik; Ian Hickson; et al. Selectors. 13 Nov 2001. W3C Candidate Recommendation. URL: http://www.w3.org/TR/2001/CR-css3-selectors-20011113

Other references

Index

  • box, #
  • check, #
  • circle, #
  • close-quote, #
  • content, #
  • contents, #
  • counter-increment, #
  • counter-reset, #
  • counters, #
  • crop, #
  • diamond, #
  • disc, #
  • display, #
  • document-url, #
  • endnote, #
  • footnote, #
  • here, #
  • hyphen, #
  • inhibit, #
  • list-item, #, #
  • <content-list>, #
  • <counters>, #
  • <strings>, #
  • move-to, #
  • no-close-quote, #
  • none, #, #, #
  • no-open-quote, #, #
  • normal, #, #, #
  • open-quote, #
  • page-policy, #
  • pending(<identifier>), #
  • quotes, #
  • scope, #
  • section-note, #
  • square, #
  • superior, #
  • superior parent, #
  • superior siblings, #

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
content | [ <uri> ',' ]* [ normal | none | inhibit | <content-list> ] | normal | all elements, ::before, ::after, ::alternate, ::marker, ::line-marker, margin areas, and @footnote areas | no | N/A | all
counter-increment | [ <identifier> <integer>? ]+ | none | note | all elements, ::before, ::after, ::alternate, ::marker, ::line-marker, margin areas, @footnote areas, and @page context | no | N/A | alll
counter-reset | [ <identifier> <integer>? ]+ | none | note | all elements, ::before, ::after, ::alternate, ::marker, ::line-marker, margin areas, @footnote areas, and @page context | no | N/A | alll
crop | <shape> | auto | auto | replaced elements | no | relative to intrinsic size | visual
display | normal | normal | all elements, ::before, ::after, ::alternate, and ::outside | no | N/A | all
move-to | normal | here | <identifier> | normal | all elements, ::before, ::after, and ::alternate | no | N/A | all
page-policy | start | first | last | start | @counter and @string blocks | N/A | N/A | paged
quotes | foo | bar | text | all elements, ::before, ::after, ::alternate, ::marker, ::line-marker, margin areas, and @footnote areas | no | N/A | visual


CSS3 Generated Content for Paged Media Module

CSS Generated Content for Paged Media Module

W3C Working Draft 08 June 2010

This version:
http://www.w3.org/TR/2010/WD-css3-gcpm-20100608
Latest version:
http://www.w3.org/TR/css3-gcpm
Previous version:
http://www.w3.org/TR/2007/WD-css3-gcpm-20070504
Editor:
Håkon Wium Lie, Opera Software, howcome@opera.com

Copyright © 2010 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

This module describes features often used in printed publications. Most of the specified functionality involves some sort of generated content where content from the document is adorned, replicated, or moved in the final presentation of the document. Along with two other CSS3 modules – multi-column layout and paged media – this module offers advanced functionality for presenting structured documents on paged media. This specification only applies to the ‘print’ media type.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css3-gcpm” in the subject, preferably like this: “[css3-gcpm] …summary of comment…”

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This functionality described in this WD is scaled down compared to earlier versions. The remaining functionality is considered to be useful, to fit well into the CSS framework, and to be within reach of implementations. Indeed, significant parts of the draft has already been implemented.

Table of contents

  • 1. Introduction
  • 2. Running headers and footers
    • 2.1. Named strings
      • 2.1.1. Setting named strings: the ‘string-set’ property
      • 2.1.2. Using named strings
    • 2.2. Running elements
  • 3. Leaders
  • 4. Cross-references
    • 4.1. The ‘target-counter’ and ‘target-counters’ values
    • 4.2. The ‘target-text’ value
  • 5. Footnotes
    • 5.1. Turning elements into footnotes
    • 5.2. The footnote area
    • 5.3. Footnote calls
    • 5.4. Footnote markers
    • 5.5. Counting footnotes
    • 5.6. Laying out footnotes
    • 5.7. Footnote magic
  • 6. Hyphenation
    • 6.1. Hyphenate properties
  • 7. New counter styles
    • 7.1. The ‘super-decimal’ list-style-type
    • 7.2. Named counter styles
    • 7.3. The ‘symbols()’ list-style-type
  • 8. Image resolution
  • 9. Page marks and bleed area
  • 10. Bookmarks
  • 11. CMYK colors
  • 12. Styling blank pages
  • 13. Page floats
    • 13.1. Float intrusion in multicol elements
  • 14. Advanced multi-column layout
    • 14.1. The ‘float-offset’ property
  • 15. Conformance
  • 16. Appendix A: Default style sheet
  • Acknowledgments
  • References
    • Normative references
    • Other references
  • Index
  • Property index

1. Introduction

(This section is not normative.)

This specification describes features often used in printed publications. Some of the proposed functionality (e.g., hyphenation, the new list style types, and border segments) may also used with other media types. However, this specification is only concerned with the ‘print’ media type.

2. Running headers and footers

To aid navigation in printed material, headers and footers are often printed in the page margins. [CSS3PAGE] describes how to place headers and footers on a page, but not how to fetch headers and footers from elements in the document. This specification offers two ways to achieve this. The first mechanism is named strings which copies the text (without style, structure, or replaced content) from one element for later reuse in margin boxes. The second mechanism is running elements which moves elements (with style, structure, and replaced content) into a margin box.

2.1. Named strings

Named strings can be thought of as variables that can hold one string of text each. Named strings are created with the ‘string-set’ property which copies a string of text into the named string. Only text is copied; not style, structure, or replaced content.

Consider this code:

h1 { string-set: title content() }

Whenever an h1 element is encountered, its textual content is copied into a named string called title. Its content can be retrieved in the ‘content’ property:

@page :right { @top-right { content: string(title) }}

2.1.1. Setting named strings: the ‘string-set’ property

Name: | string-set
Value: | [[ <identifier> <content-list>] [, <identifier> <content-list>]* ] | none
Initial: | none
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | all
Computed value: | as specified value

The ‘string-set’ property accepts a comma-separated list of named strings. Each named string is followed by a content list that specifies which text to copy into the named string. Whenever an element with value of ‘string-set’ different from ‘none’ is encountered, the named strings are assigned their respective value.

For the ‘string-set’ property, <content-list> expands to one or more of these values, in any order:

<string>
a string, e.g. "foo"
<counter>
the counter() or counters() function, as per CSS 2.1 section 4.3.5
<content>
the ‘content()’ function returns the content of elements and pseudo-elements. The functional notation accepts an optional argument:
‘content()’
Without any arguments, the function returns the textual content of the element, not including the content of its ::before and ::after pseudo-element. The content of the element's descendants, including their respective ::before and ::after pseudo-elements, are included in the returned content.
‘content(before)’
The function returns the textual content of the ::before pseudo-element the content of the element.
‘content(after)’
The function returns the textual content of the ::after pseudo-element the content of the element.
‘content(first-letter)’
The function returns the first letter of the content of the element. The definition of a letter is the same as for :first-letter pseudo-elements.

The expected use for ‘content(first-letter)’ is to create one-letter headers, e.g., in dictionaries.

‘env()’
This function returns data from the local environment of the user at the time of formatting. The function accepts one of these keywords:
  • env(url): returns the URL of the document
  • env(date): returns the date on the user's system at the time of formatting
  • env(time): returns the time on the user's system at the time of formatting
  • env(date-time): returns the date and time on the user's system at the time of formatting

Information about date and time is formatted according to the locale of the user's system.

Or, should there be a way to specify the locale? Or should we simply format all in ISO format (e.g., 2010-03-30)?

On many systems, preformatted strings in the user's locale can be found through the strftime function. The date, time and date-time strings can be found by using the "%x", "%X" and "%c" conversion strings, respectively.

@page {
  @top-right { content: env(url) }
  @bottom-right { content: env(date-time) }
}

Named strings can only hold the result of one assignment; whenever a new assignment is made to a named string, its old value is replaced.

User agents, however, must be able to remember the result of more than one assignment as the ‘string()’ functional value (described below) can refer to different assignments.

The scope of a named string is the page of the element to which the ‘string-set’ property is attached and subsequent pages.

The name space of named strings is different from other sets of names in CSS.

The ‘string-set’ property copies text as well as white-space into the named string.

h2 {
  string-set: header "Chapter " counter(header) ": " content();
  counter-increment: header;
}

Note that the string called "header" is different from the counter with the same name. The above code may result in header being set to "Chapter 2: Europa".

This example results in the same value being assigned to header as in the previous example.

h2:before { content: "Chapter " counter(header) }
h2 {
  string-set: header content(before) content();
  counter-increment: header }

dt { string-set: index content(first-letter) }

The content is copied regardless of other settings on the element. In this example, H1 elements are not displayed, but their content is copied into the named string.

h1 {
  display: none;
  string-set: header content();
}

2.1.2. Using named strings

The content of named strings can be recalled by using the ‘string()’ value on the ‘content’ property. The ‘string()’ value has one required argument, namely the name of the string.

@page { @top-center { content: string(header) }}
@page { @right-middle { content: string(index) }}
@page { @top-left { content: string(entry) }}
h1 { string-set: header "Chapter " counter(chapter) content() }
dt { string-set: index content(first-letter), entry content() }

If the value of the named string is changed by an element on a certain page, the named string may have several values on that page. In order to specify which of these values should be used, an optional argument is accepted on the ‘string()’ value. This argument can have one of four keywords:

  • ‘start’: the named string's entry value for that page is used.
  • ‘first’: the value of the first assignment is used. If there is no assignment on the page, the start value is used. ‘first’ is the default value.
  • ‘last’: the named string's exit value for that page is used
  • ‘first-except’: similar to ‘first’, except on the page where the value was assigned. On that page, the empty string is used.

In this example, the first term on the page will be shown in the top left corner and the last term on the page will be shown in the top right corner. In top center of the page, the first letter of first term will be shown.

@page { @top-left { content: string(term, first) }}
@page { @top-right { content: string(term, last) }}
@page { @top-center { content: string(index, first) }}
dt { string-set: index content(first-letter), term content() }

In this example, the header in the top center will be blank on pages where ‘h1’ elements appear. On other pages, the string of the previous ‘h1’ element will be shown.

@page { @top-center { content: string(chapter, first-except) }}
h1 { string-set: chapter content() }

If the named string referred to in a ‘string()’ value has not been assigned a value, the empty string is used.

2.2. Running elements

Named strings, as described above, can only hold textual content; any style, structure or replaced content associated with the element is ignored. To overcome this limitation, a way of moving elements into running headers and footers is introduced.

Elements that are moved into headers and footers are repeated on several pages; they are said to be running elements. To support running elements, a new value – running() – is introduced on the ‘position’ property. It has one required argument: the name by which the running element can be referred to. A running element is not shown in its natural place; there it is treated as if ‘display: none’ had been set. Instead, the running element may be displayed in a margin box.

Like counters and named strings, the name of a running element is chosen by the style sheet author, and the names have a separate name space. A running element can hold one element, including its pseudo-elements and its descendants. Whenever a new element is assigned to a running element, the old element is lost.

User agents, however, must be able to remember the result of more than one assignment as the ‘element()’ value (described below) can refer to different assignments.

Running elements inherit through their normal place in the structure of the document.

title { position: running(header) }
@page { @top-center {
  content: element(header) }
}

Like the ‘string()’ value, the ‘element()’ value accepts an optional second argument:

‘start’
‘first’
‘last’
‘first-except’

The keywords have the same meaning as for the ‘string()’ value.

The ‘element()’ value cannot be combined with any other values.

In this example, the header is hidden from view in all media types except print. On printed pages, the header is displayed top center on all pages, except where h1 elements appear.

<style>
  div.header { display: none }
  @media print {
  div.header {
    display: block;
    position: running(header);
  }
  @page { @top-center { content: element(header, first-except) }}
</style>
...
<div class="header">Introduction</div>
<h1 class="chapter">An introduction</div>

This code illustrates how to change the running header on one page in the middle of a run of pages:

...
<style>
@page { @top-center {
  content: element(header, first) }}
.header { position: running(header) }
.once { font-weight: bold }
</style>
...
<div class="header">Not now</div>
<p>Da di ha di da di ...
  <span class="header once">NOW!</span>
  <span class="header">Not now</span>
  ... da di ha di hum.</p>
...
The header is "Not now" from the outset, due to the "div" element. The first "span" element changes it to "NOW!" on the page where the "span" element would have appeared. The second "span" element, which would have appeared on the same page as the first is not used because the ‘first’ keyword has been specified. However, the second "span" element still sets the exit value for "header" and this value is used on subsequent pages.

3. Leaders

A leader is a visual pattern that guides the eye. Typically, leaders are used to visually connect an entry in a list with a corresponding code. For example, there are often leaders between titles and page numbers in a table of contents (TOC). Another example is the phone book where there are leaders between a name and a telephone number.

In CSS3, a leader is composed of series of glyphs through the ‘leader()’ value on the ‘content’ property. The functional notation accepts one value which describes the glyph pattern that make up the leader. These values are allowed:

  • leader(dotted)
  • leader(solid)
  • leader(space)
  • leader(<string>)

Using the keyword values is equivalent to setting a string value. The table below shows the equivalents:

Keyword | String | Unicode characters
leader(dotted) | leader(‘. ’) | \002E \0020
leader(solid) | leader(‘_’) | \005F
leader(space) | leader(‘ ’) | \0020

The string inside the parenthesis is called the leader string.

In its simplest form, the ‘content’ property only takes one ‘leader()’ value:

heading::after { content: leader(dotted) }

The leader string must be shown in full at least once and this establishes the minimum length of the leader. To fill the available space, the leader string is repeated as many times as possible in the writing direction. At the end of the leader, a partial string pattern may be shown. White space in leaders is collapsed according to the values on white-space properties.

These properties influence the appearance of leaders: all font properties, text properties, ‘letter-spacing’, white-space properties, background properties, and ‘color’.

User Agents should attempt to align corresponding glyphs from the leader pattern between consecutive lines.

In a more complex example, the ‘leader’ value is combined with other values on the ‘content’ property:

ul.toc a::after {
  content: leader(". . . ") target-counter(attr(href, url), page);
}

If the content connected by a leader end up on different lines, the leader will be present on all lines. Each leader fragment honors the minimum length of the leader.

Consider this code:

<style>
.name::after { content: leader(dotted) }
</style>
<div class="entry">
<span class="name">John Doe</span>
<span class="number">123456789</span>
</div>

If the name and number end up on different lines (e.g., in a narrow column), it may be formatted like this:

John Doe....
...123456789

To determine the length of the leaders, user agents must do the following for each line:

  1. Lay out the content with leaders of minimum lengths
  2. Determine the empty space left on the line.
  3. Distribute the empty space between the leaders on the line. Glyphs must not be shown partially. All leaders on the line should, to the extent possible, have the same length. This may not always be possible as the minimum leader length must be honored.
  4. Fill the empty space with the specified leader pattern.

Consider this code:

<style>
cite::before { content: leader('  ') }
</style>
<blockquote>
  Bla great bla bla world bla bla
  empire bla bla color bla bla
  history bla bla forever.
    <cite>John Johnson</cite>
</blockquote>

Depending on the width of the containing block, this may be rendered as:

  Bla great bla bla world bla bla
  empire bla bla color bla bla
  history bla bla forever.   John
  Johnson

However, this rendering is preferable:

  Bla great bla bla world bla bla
  empire bla bla color bla bla
  history bla bla forever.
                     John Johnson

To indicate that John Johnson should be kept on one line, this rule can be added to the style sheet:

cite { text-wrap: suppress }

Until ‘text-wrap’ is widely supported, this rule can also be used:

cite { white-space: nowrap }

If the containing element is wider, this may be the resultant presentation:

  Bla great bla bla world bla bla empire
  bla bla color bla bla history bla bla
  forever.                  John Johnson

4. Cross-references

It is common to refer to other parts of a document by way of a section number (e.g., "See section 3.4.1"), a page number (e.g., "See discussion on page 72"), or a string (e.g., "See the chapter on Europe"). Being able to resolve these cross-references automatically saves time and reduces the number of errors.

4.1. The ‘target-counter’ and ‘target-counters’ values

Numerical cross-references are generated by ‘target-counter()’ and ‘target-counters()’ values that fetch the value of a counter at the target end of the link. These functions are similar to the ‘counter()’ and ‘counters()’ functions, except that they fetch counter values from remote elements. ‘target-counter()’ has two required arguments: the url of the link, and the name of a counter. ‘target-counters()’ has three required arguments: the url of the link, the name of a counter, and a separator string. Both functions accepts an optional argument at the end that describes which list style type to use when presenting the resulting number; ‘decimal’ being the default.

This style sheet specifies that a string like " (see page 72)" is added after a link:

a::after { content: "(see page " target-counter(attr(href, url), page, decimal) ")" }

This style sheet specifies that a string like " (see section 1.3.5)" is added after a link:

a::after { content: "(see section " target-counters(attr(href, url), section, ".", decimal) ")" }

4.2. The ‘target-text’ value

Textual cross-references are generated by ‘target-text()’ which fetches the textual content from the target end of the link. Only text is copied; not style, structure, or replaced content. ‘target-text()’ has one required argument: the url of the link. An optional second argument specifies exactly which content is fetched. There are four possible values:

‘content()’
refers to the textual content of the element, not including the content of its ::before and ::after pseudo-element. The content of the element's descendants, including their respective ::before and ::after pseudo-elements, are included in the returned content.
‘content(before)’
refers to the content of the element's ::before pseudo-element. This is the default value.
‘content(after)’
refers to the content of the element's ::after pseudo-element
‘content(first-letter)’
refers to the first letter of the textual content of the element, not including the content of its ::before and ::after pseudo-element.

To generate this text

See Chapter 3 ("A better way") on page 31 for an in-depth evaluation.

from this markup:
<p>See <a href="#chx">this chapter</a> for an in-depth evaluation.
...
<h2 id="chx">A better way</h2>
this CSS code can be used:
h2 { counter-increment: chapter }
a { content: "Chapter " target-counter(attr(href, url), chapter)
   ' ("'  target-text(attr(href), content()) '") on page '
   target-counter(attr(href, url), page);

5. Footnotes

A footnote is a note typically placed at the bottom of a page that comments on or cites a reference. References to footnotes are marked with a note-call in the main text. The rendering of footnotes is complex. As far as possible, footnotes try to reuse other parts of CSS. However, due to the typographic traditions of footnotes, some new functionality is required to support footnotes in CSS:

In order to support footnotes in CSS, the following functionality is added:

  • one new value on the ‘float’ property: ‘footnote’
  • one new page area: ‘@footnote’
  • two new pseudo-elements: ‘::footnote-call’ and ‘::footnote-marker’
  • one predefined counter: ‘footnote’
  • one new value on the ‘content’ property: ‘target-pull()’
  • border segments
  • two new ‘list-style-type’ values: ‘super-decimal’, and symbol(...)

In its simplest form, making a footnote is simple.

<style>
.footnote { float: footnote }
</style>

<p>A sentence consists of words. <span class="footnote">Most often.</span>.

In this example, the text Most often. will be placed in a footnote. A note-call will be left behind in the main text and a corresponding marker will be shown next to the footnote. Here is one possible rendering:

A sentence consists of words. ¹

¹ Most often.

To support legacy browsers, it is often better to make a link to the note rather than including the text inline. This example shows how to fetch the content of a note and place it in a footnote.

<style>
@media print {
  .footnote {
    float: footnote;
    content: target-pull(attr(href, url)) }
  .call { display: none }
}
</style>
...
<p>A sentence consists of words<a class="footnote" href="#words"> [3]</a>.
...
<p id=words><span class="call">[3]</span> Most often.

When shown in a legacy browser, the content of the element will be shown as a clickable link to an endnote. When printed according to this specification, there will be a footnote:

A sentence consists of words¹.

¹ Most often.
Consider this markup:
<p>Sorry, <span title="This is, of course, a lie.">we're closing for lunch</span>.

The content of the "title" attribute can be turned into a footnote with this code:

span[title]::after {
  content: attr(title);
  float: footnote;
}

5.1. Turning elements into footnotes

An element with ‘float: footnote’ (called a footnote element) is moved to the footnote area and a footnote-call pseudo-element is put in its original place.

span.footnote {
  float: footnote;
}

Footnote elements are presented inside the footnote area, but they inherit through their normal place in the structure of the document.

The ‘display’ property on footnote elements is ignored. Instead, the value of the ‘display’ property in the @footnote context determines if footnotes are block or inline elements.

In this example, the footnotes are displayed inline:

@footnote {
  display: inline;
}
span.footnote {
  float: footnote;
}

Here is one possible presentation of inline footnotes:

¹ The first footnote. º The second footnote.

For each new footnote element, the ‘footnote’ counter is automatically incremented.

5.2. The footnote area

All elements with ‘float: footnote’ are moved to the footnote area. The footnote area is described by an @footnote-rule inside the @page-rule. By default, the footnote area appears at the bottom of the page, but it can be positioned in other places.

Should the footnote are be positioned using page floats or (fixed?) absolute positioning? Or both?

@page {
  @footnote {
    float: bottom page;
    width: 100%;
  }
}

These rules place the footnote area in the bottom left corner of the page:

@page {
  @footnote {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 5em;
  }
}

Inside @footnote, the ‘gr’ unit is based on the oldest multicol element in the document.

This code places the footnote area at the bottom of the right column:

@page {
  @footnote {
    float: bottom right multicol;
    width: 1gr;
  }
}

The content of the footnote area is considered to come before other content which may compete for the same space on the same page.

@page { @footnote { float: bottom page}}
div.figure { float: bottom page }

If figures and footnotes are on the same page, the footnotes will appear below the figures as they are floated to the bottom before the figures.

Potentially, every page has a footnote area. If there are no footnotes on the page, the footnote area will not take up any space. If there are footnotes on a page, the layout of the footnote area will be determined by the properties/values set on it, and by the footnote elements elements inside it.

These properties apply to the footnote area: ‘content’, ‘border’, ‘padding’, ‘margin’, ‘height’, ‘width’, ‘max-height’, ‘max-width’, ‘min-height’, ‘min-width’, the background properties.

This example uses some of the applicable properties on @footnote:

@footnote {
  margin-top: 0.5em;
  border-top: thin solid black;
  border-clip: 4em;
  padding-top: 0.5em;
}

The result of this code is a footnote area separated from other content above it by margin, border and padding. Only 4em of the border is visible due to the ‘border-clip’ property, which is defined in CSS Backgrounds and Borders Module Level 4 [CSS4BACKGROUND].

5.3. Footnote calls

When an element is moved to the footnote area, a footnote-call is left behind. By default, User Agents must behave as if this code is part of the default style sheet:

::footnote-call {
  content: counter(footnote, super-decimal);
}

The resulting note call is a super-script decimal number.

5.4. Footnote markers

A ::footnote-marker pseudo-element is added to each footnote element, in the same place, and replacing, the ::before pseudo-element. User agents must, by default, show the "footnote" counter in the footnote-marker.

User Agents may display footnote-calls and footnote-markers this way by default:

::footnote-call {
  content: counter(footnote, super-decimal);
}
::footnote-marker {
  content: counter(footnote, super-decimal);
}

Marker elements are discussed in more detail in the CSS Lists module [CSS3LIST]. One suggested change to that module is to honor the value of ‘list-style-position’ on the ::footnote-marker pseudo-element itself rather than the corresponding list-item element. Further, one clarification to the horizontal placement of the marker is suggested: the margin box of the marker box is horizontally aligned with the start of the line box.

5.5. Counting footnotes

The "footnote" counter is automatically incremented each time a footnote is generated. That is, the "footnote" counter is incremented by one each time an element with ‘float: footnote’ appears.

The footnote counter can be reset with the ‘counter-reset’ property.

This code resets the "footnote" counter on a per-page page basis:
@page { counter-reset: footnote }

Should one also be able to manually increment the "footnote" counter?

5.6. Laying out footnotes

Footnotes must appear as early as possible under the following constraints:

  1. A footnote marker may not appear on an earlier page than the footnote call.
  2. Footnotes may not appear out of document order.
  3. The footnote area is limited in size by ‘max-height’, unless the page contains only footnotes. (E.g., if at the end of the document there are still footnotes unprinted, the User Agent can use the whole page to display footnotes.)
  4. If there is a footnote call on a page, the footnote area may not be empty, unless its ‘max-height’ is too small.

5.7. Footnote magic

When an element is turned into a footnote, certain magical things happen. The element is moved to the footnote area, a footnote call is left behind in its place, a footnote marker is displayed before the element, and the footnote counter is incremented.

When rendering footnotes, User Agents may apply certain heuristics to improve the presentation. For example, the space between a footnote-call and surrounding text may be adjusted. Another example is the height of the footnote area; it may be heuristically constrained to limit the area that is used for footnotes.

6. Hyphenation

Hyphenation means splitting words to improve the layout of paragraphs. This specifications does not define the exact rules for hyphenation, but describes six properties that influence hyphenation.

6.1. Hyphenate properties

Name: | hyphens
Value: | none | manual | auto
Initial: | manual
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value

Values are:

none
Words are not broken at line breaks, even if characters inside the word suggest line break points.
manual
Words are only broken at line breaks where there are characters inside the word that suggest line break opportunities. Characters can be explicit or conditional.

In Unicode, U+00AD is a conditional "soft hyphen" and U+2010 is an explicit hyphen. Unicode Standard Annex #14 describes the role of soft hyphens in the Unicode Line breaking algorithm.

In HTML, &shy; represents the soft hyphen character which suggests a line break opportunity.

ex&shy;ample.
auto
Words can be broken at appropriate hyphenation points, as determined by characters inside the word, resources listed in ‘hyphenate-resource’, or other UA-dependent resources. Characters inside the word take priority over hyphenation points determined by other resources.
Name: | hyphenate-resource
Value: | none | <uri> [, <uri> ]*
Initial: | none
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value

This property specifies a comma-separated list of external resources that can help the UA determine hyphenation points. If more than one resource is specified, the UA should consult each resource until it finds one that is able to determine hyphenation points in a word. The ‘none’ value indicates that no external resources are available. In any case, the UA can also use local resources not listed on this property.

Often, finding the right hyphenate resource is based on knowing the language of the text. The lang attribute is recommended for encoding the language, and the corresponding selector is used in this example:

:lang(dk) { hyphenate-resource: url("hyph_da_DK.dic"), url("hyph_da_NO.dic") }
POWERED BY HeroNote
Name: | hyphenate-before
Value: | <integer> | auto
Initial: | auto
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value

This property specifies the minimum number of characters in a hyphenated word before the hyphenation character. The ‘auto’ value means that the UA chooses a value that adapts to the current layout.

Unless the UA is able to calculate a better value, it is suggested that ‘auto’ means 2.

Name: | hyphenate-after
Value: | <integer> | auto
Initial: | auto
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value

This property specifies the minimum number of characters in a hyphenated word after the hyphenation character. The ‘auto’ value means that the UA chooses a value that adapts to the current layout.

Unless the UA is able to calculate a better value, it is suggested that ‘auto’ means 2.

Name: | hyphenate-lines
Value: | no-limit | <integer>
Initial: | no-limit
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value

This property indicates the maximum number of successive hyphenated lines in an element. In some cases, user agents may not be able to honor the specified value. The ‘no-limit’ value means that there is no limit.

Name: | hyphenate-character
Value: | auto | <string>
Initial: | auto
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value

This property specifies a string that is shown when a hyphenate-break occurs. The ‘auto’ value means that the user agent should find an appropriate value.

In Latin scripts, the hyphen character (U+2010) is often used to indicate that a word has been split. Normally, it will not be necessary to set it explicitly. However, this can easily be done:

article { hyphenate-character: "\2010" }

7. New counter styles

7.1. The ‘super-decimal’ list-style-type

This section will be moved to css3-lists (minutes)

A new list-style-type, ‘super-decimal’, is introduced to better support footnotes. Small, super-script footnote calls are common; the first three numbers have code points in Latin-1 and some font families have even more super-script glyphs. The ‘super-decimal’ keyword allow these font resources to be used and replaces the use of ‘font-size’ and ‘vertical-align’ (which prohibit the use of special-purpose glyphs).

This example specifies that footnote markers should consist of super-script decimal numbers.
::footnote-marker { content: counter(footnote, super-decimal) }

Using super-script glyphs is optional; UAs may also scale and position other glyphs for use in footnote calls.

7.2. Named counter styles

CSS defines a number of predefined list style types for the ‘list-style-type’ property and other places where a list-style-type value is accepted. Some styles repeat the same glyph (e.g., ‘disc’ and ‘circle’) while others have lists of glyphs (e.g., ‘decimal’, and ‘lower-roman’). To increase the range of lists that can be achieved through CSS without adding many new keywords, @counter-style rules are introduced. By using @counter-style, a style sheet can name new counter styles.

An @counter-style rule consists of the keyword ‘@counter-style’, followed by the name of the symbol counter style, followed by a space-separated list of strings.

@counter-style daggers "*" "\2020" "\2021" "\A7" "#";
ol { list-style-type: daggers }

@counter-style ordinal "1st" "2nd" "3rd" "4th";
h1:before { content: counter(chapter, ordinal) " chapter" }

The first string in the list represents number one, the second string represents number two, etc. Outside the range of specified values, the rendering will be as if the ‘decimal’ list style type had been specified.

Consider this example:

@counter-style ordinal "1st" "2nd" "3rd" "4th";
ordered-list { counter-reset: items -1 }
list-item { counter-increment: items 2 }

For a series of list-item elements inside an ordered-list element, the value of the items counter will be -1, 1, 3, 5, 7 etc. Given that the ordinal counter style only defines a counter style for 1, 2, 3, and 4, the list will be numbered "-1", "1st", "3rd", "5", "7" etc.

Named counter styles can be imported through @import statements.

@import url(http://www.example.com/armenian-counters.css); /* defines 'armenian' */
ol { list-style-type: armenian }

7.3. The ‘symbols()’ list-style-type

A new list-style-type with a functional notation is introduced to avoid the indirection of having to name counter styles. The ‘symbols()’ value takes a comma-separated list of strings as arguments.

::footnote-call {
    content: counter(footnote, symbols('*', '+', '!'))
}

Outside the range of specified values, the rendering will be as if the ‘decimal’ list style type had been specified.

This code:
ol { list-style: symbols("*", "\2020", "\2021", "\A7", "#") }
will result in these list-items markers: * † ‡ § # 6 7 8 ...

8. Image resolution

Image resolution, as the term is used in this document, means pixels per physical length, e.g., pixels per inch. Some image formats can record information about the resolution of images. This information can be helpful when determining the actual size of the image in the formatting process. However, the information can also be wrong, in which case it should be ignored. The ‘image-resolution’ and ‘background-image-resolution’ properties are introduced to determine the correct resolution of images.

Name: | image-resolution
Value: | normal | [ from-image || <dpi> ]
Initial: | normal
Applies to: | replaced elements and background images?
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | as specified value (or, should it be only one value?)

The values are:

normal
The resolution of the image is unknown, and UAs should not use the resolution found in the image. Instead, the image resolution will be found by converting the dimension of the image into CSS pixels.
from-image
The UA must look for the resolution in the image itself. If the image does not have a resolution, the specified <dpi> value is used. If no <dpi> value is specified, the behavior is as if ‘normal’ had been specified.
<dpi>
The value consists of a number with a ‘dpi’ unit identifier. The <dpi> value sets the resolution of the image. In combination with ‘from-image’, the specified dpi is only used if the image does not have a resolution.

This rule specifies that the UA should use the image resolution found in the image itself.

img { image-resolution: from-image }

Using this rule, the image resolution is set to 300dpi and the resolution in the image, if any, is ignored.

img { image-resolution: 300dpi }

These rules both specify that the UA should use the image resolution found in the image itself. If the image has no resolution, the resolution is set to 300dpi.

img { image-resolution: from-image 300dpi }
img { image-resolution: 300dpi from-image }

9. Page marks and bleed area

The ‘marks’ property from [CSS2] is part of this specification.

Name: | marks
Value: | [ crop || cross ] | none
Initial: | none
Applies to: | page context
Inherited: | no
Percentages: | N/A
Media: | visual, paged
Computed value: | specified value

This property adds crop and/or cross marks to the document. Crop marks indicate where the page should be cut. Cross marks are used to align sheets.

Crop marks and cross marks are printed outside the page box. To have room to show crop and cross marks, the final pages will have to be somewhat bigger than the page box.

To set crop and cross marks on a document, this code can be used:

@page { marks: crop cross }

Name: | bleed
Value: | <length>
Initial: | 6pt
Applies to: | page context
Inherited: | no
Percentages: | refer to width of page box
Media: | visual
Computed value: | as specified value

This property specifies the extent of the page bleed area outside the page box. This property only has effect if crop marks are enabled.

10. Bookmarks

Some document formats have the capability of holding bookmarks. Bookmarks are typically shown outside the document itself, often a tree-structured and clickable table of contents to help navigate in the electronic version of the document. To generate bookmarks, these properties are defined:

Name: | bookmark-level
Value: | none | <integer>
Initial: | none
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | all
Computed value: | specified value

This property describes what level a certain bookmark has in a hierarchical bookmark structure. The highest level is ‘1’, then ‘2’, ‘3’ etc.

h1 { bookmark-level: 1 }
h2 { bookmark-level: 2 }
h3 { bookmark-level: 3 }

Name: | bookmark-label
Value: | content() | attr() | <string>
Initial: | content()
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | all
Computed value: | specified value

This property specifies the label of the bookmark, i.e., the text that will represent the bookmark in the bookmark structure.

a { bookmark-label: attr(title, string) }
h1 { bookmark-label: content() }
h2 { bookmark-label: content(before) }
#frog { bookmark-label: "The green frog" }

Name: | bookmark-target
Value: | none | <uri> | <attr>
Initial: | none
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | all
Computed value: | For URI values, the absolute URI; for attr() values, the resulting URI or string; for other keywords, as specified.

This property specifies the target of the bookmark link.

.bookmark {
   bookmark-label: attr(title, string);
   bookmark-target: attr(href, url);
}
...
<a class="bookmark" title="The green pear" href="#pears"/>
.exable { bookmark-label: url(http://www.example.com) }
Name: | bookmark-state
Value: | open | closed
Initial: | open
Applies to: | block-level elements
Inherited: | no
Percentages: | N/A
Media: | all
Computed value: | specified value

This property describes the initial state of a bookmark.

* { bookmark-state: closed }
#open { bookmark-state: open }

11. CMYK colors

Printers do not use RGB colors, they (often) use CMYK: cyan, magenta, yellow and black. The ‘cmyk()’ functional value allows style sheets to express device-dependent CMYK colors.

h3 { color: cmyk(0.8, 0.5, 0.0, 0.3) }

The values representing the colors are between ‘0’ and ‘1’. Values outside this range are clipped.

It is not expected that screen-centric user agents support CMYK colors and it is therefore important that existing CSS color values can be combined with CMYK colors.

h3 {
  color: red;
  color: cmyk(0.5, 0.1, 0.0, 0.2);
}

User Agents that do not understand the cmyk() value, will use the first color (red). User agents that understand cmyk() will use the second color (which is bluish).

12. Styling blank pages

Blank pages that appear as a result of forced page breaks can be styled with the :blank pseudo-class.

In this example, forced page break may occur before h1 elements.

h1 { page-break-before: left }

@page :blank {
  @top-center { content: "This page is intentionally left blank" }
}

The :blank pseudo-class has the same specificity as the :first pseudo-class. A page matched by :blank will still be matched by other page selectors.

If headers have been specified on all right pages, a blank right page will be matched by both :blank and :right. Therefore, margin boxes set on right pages will have to be removed unless they are wanted on blank pages. Here is an example where the top center header is removed from blank pages, while the page number remains:

h1 { page-break-before: left }

@page :blank {
  @top-center { content: none }
}

@page :right {
  @top-center { content: "Preliminary edition" }
  @bottom-center { content: counter(page) }
}

Due to the higher specificity of :blank over :right, the top center header is removed even if content: none comes before content: "Preliminary edition".

13. Page floats

Images and figures are sometimes displayed at the top or bottom of pages. Also, an element may be moved to the next page or not displayed at all if there is not enough room on its native page. These types of floats are called "page floats" in this specification.

To support page floats, the ‘float’ property is extended with several new values:

inside
On a right page, this value is synonymous with ‘left’. On a left page, this value is synonymous with ‘right’.
outside
On a left page, this value is synonymous with ‘left’, On a right page, this value is synonymous with ‘right’.
page
Indicates that the page area is the flow root for the element.
multicol
Indicates that the multicol element is the flow root for the element.
intrude
The element may intrude neighboring columns; if the element is not in a multi-column element, this keyword has no effect.
unless-room
If the element can be laid out in its natural position without causing a page break, it should be laid out there disregarding the ‘float’ property; in other cases the other values on ‘float’ will determine its floating behavior.
top
This keyword indicates that the element is floated to the top of the flow root.
bottom
This keyword indicates that the element is floated to the bottom of the flow root.
next
The float is placed on top of the next page from its source location. If combined with ‘bottom’, the float is placed on the bottom of the next page.
page()
The element is floated to a named page. The named page is created for the element, unless a suitable named page already has been created by another ‘page()’ value. The name page should appear as early as possible, but any ‘next’ keywords should be honored.
The element is floated to one or more named pages of the type specified. These named pages are created for the purpose of showing the element, and they are presented as early as possible after the page from which they are displaced. If the element is not the first page float to be displaced from this page area to this named page name, its contents should continue on the last of the previously established named pages (unless precluded, for example by page-breaking properties).
hide
As if ‘display: none’ is set.

The values on float are categorized as such:

  • horizontal keywords: left right inside outside
  • vertical keywords: top bottom
  • flow root keywords: page multicol
  • modifier keyword: next unless-room
  • other keywords: none hide footnote page()

The keywords can be combined to form more complex expressions with these restrictions:

  • only one horizontal keyword can appear in a set
  • only one vertical keyword can appear in a set
  • at least one horizontal or vertical keyword must appear, except that ‘none’, ‘hide’, and ‘footnote’ must appear alone
  • ‘next’ may appear once along with ‘page’
  • keywords can appear in any order

Float element to the top of the page:

.figure {
  float: top page;
}

Float element to the top of the next page:

.figure {
  float: top next page;
}

Place footnotes at the bottom of the inside columns:

@footnote {
  float: bottom inside multicol;
}

Place figure on top of current column:

.figure {
  float: top;
}

Float the figure to the top of the next page, unless it fits in its natural position without causing a page break:

.figure {
  float: top next page unless-room;
}

Hide the element unless it fits in its natural position without causing a page break:

.figure {
  float: hide unless-room;
}

In this example, wide tables are floated to landscape pages:

table.wide {
  float: page(landscape);
}
In the above code, the element is take out of the flow, which is allowed to continue on the same page. If the flow should be broken, this code can be used:
table.wide {
  page: landscape;
}

Consider this code:

table {
  float: page(landscape);
}

If two tables appear consecutively, they will both, space permitting, be placed on the same named page. To ensure that each table appears on its own page, this code can be used:

table {
  float: page(landscape);
  page-break-before: always;
}

For non-replaced elements in horizontal text, values on ‘float’ that have a horizontal component (‘right’, ‘left’, ‘outside’, ‘inside’) will result in shrink-wrap width calculations as per CSS 2.1 section 10.3.5. Values that only have a vertical component (‘top’, ‘bottom’, ‘next’, not in combination with other values) will result in width calculations as per CSS 2.1 section 10.3.3. In vertical text, width calculations are vice versa.

13.1. Float intrusion in multicol elements

In multi-column layouts [CSS3COL], floats appear within columns; they never intrude into neighboring columns.

img { float: left; width: 120% }

In this example, the image is wider than the column and will therefore intrude into the neighboring column. At the bottom of the middle column is a long word that is clipped in the middle of the column gap.

Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc

def g hij klm nopqrs
tuv wxy z. Abc de fg

hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.
M nop qrst uvw
x yz. Ab cde fgh
i jkl. Mnopqr stu
vw xyz. A bcdef
ghij klm nopqrs
tuv wxy z. Abc
de fghi jk klmop qrst
uvwxyzabcdefghijklmn

Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.
M nop qrst uv wx yz.
Ab cde fgh i jkl. Mno
pqr stu vw xyz.

img { float: right; width: 120% }

In this example, the image naturally appears in the last column. Due to being floated to the right, the image will intrude into the neighboring column to the left.

Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw
x yz. Abc def ghi j
kl. M nop qrst uv wx
yz. Ab cde fgh i jkl
mno pqr stu vw xyz.

Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nop
qrs tuv wxy z.
Rst uvw x yz. Ab
c def ghi jkl m.
Nop qrst uv wx
Ryz. Ab cdef gh
i jklmno pqr stu vw

xyz. Abc def ghi jkl
mno. Pqr stu vw xyz.

Ab cde fgh ij klm no.

14. Advanced multi-column layout

In paged media, it is common for figures, captions, images, and quotes to be laid out in certain positions for typographical reasons, rather than for structural (as in content order) reasons. For example, an image that illustrates a news story is often placed in the upper right corner of the article, irrespective of its order in the content. A poignant quote from the article may be shown in large type in the column gap, pushing aside text in both columns, to get the attention of the reader.

Basic multi-column layouts is described in a separated CSS3 module [CSS3COL]. This section extends multi-column functionality so that more advanced, but commonly used, layouts can be achieved.

The proposed functionality relies on three new components:

  • one new value on float: ‘multicol’ (listed in the previous section)
  • one new property: ‘float-offset’
  • one new unit: ‘gr’

The strategy for achieving advanced multi-column layout is similar to page floats; elements escape their normal flow root by setting a value on ‘float’. In the case of multi-column layout, the keyword is ‘multicol’ (instead of ‘page’) and it indicates that the element should floated with regard to. the multi-column element instead of the column where it naturally occurs.

To further enhance positioning, the ‘float-offset’ property is introduced. It pushes elements in the opposite direction of the positional keywords, both horizontally and vertically.

The ‘gr’ unit is introduced to allow the grid lines of columns (and, potentially, tables) to be used in the positioning ans sizing of elements. Each column has one grid line on each side corresponding to the content edge of the content box.

The ‘gr’ unit has two purposes. When used on the ‘float-offset’ property it identifies a position by counting columns and gaps from the position established by the ‘float’ property. Fractions on the ‘gr’ unit refer to fractions of the last counted gap or column.

When used on the ‘width’ property, the ‘gr’ unit identifies a length by counting gaps and columns, starting at the point where the element naturally finds itself and continuing in the direction of box expansion. Fractions on the ‘gr’ unit refer to the last gap or column counted.

14.1. The ‘float-offset’ property

Name: | float-offset
Value: | <length> <length> ?
Initial: | 0 0
Applies to: | floated elements
Inherited: | no
Percentages: | refer to width and height of containing block
Media: | visual, paged
Computed value: | one or two absolute lengths

This property pushes floated elements in the opposite direction of the where they have been floated with ‘float’. If one value is specified, it is the horizontal offset. If two values are specified, the first is the horizontal and the second is the vertical offset. If an element has only been floated horizontally (e.g., by setting ‘float: right’), this property will only offset the float horizontally, even if a vertical value also has been specified. Likewise, if an element has only been floated vertically, this property will only offset the float vertically. If an element has been floated both horizontally and vertically, this property will offset both horizontally and vertically. If no vertical value has been specified, the vertical offset is set to zero.

If the ‘gr’ unit or percentage unit is used, it means that the middle of the float should be aligned with the specified grid line (or portion thereof).

If another unit is used, it means that the float is pushed a distance equal to the specified length.

‘float-offset’ is a good concept for moving a float into the right position. For completeness it should apply to absolute positioning as well. We should reuse existing naming conventions already in place for abspos elements (e.g., 'offset-left, ‘right’, or call it ‘shift left, ’shift right' etc.).

This code serves as the base document for the examples of this section:

<html>
<style>
div {
  column-width: 15em;
  column-gap: 2em;               /* shown in red below */
  column-rule: thin solid black; /* shown in black below */
  padding: 1em;                  /* shown in blue below */
}
img {
  display: block;                /* shown in dark gray below */
}
</style>
<body>
<div>
Lorem ipsum dolor sit amet. Nam at jus.
<img src="foo"/>
Sed imp er di et ris. Cur abi tur et sapen.
...
</div>
</body>
</html>

This code can be rendered as:

Lorem ipsum dolor
sit amet. Nam at jus.

Sed imp er di et ris.
Cur abi tur et sapen.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

If this code is added to the base document:

img { float: right }

it may be rendered as:

Lorem ipsum dolor
sit amet. Nam at jus.
Sed
imp
er di
et ris.
Cur
abi
tur et sapen. Fusce
sed ligula a turpis.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

This code floats images to the bottom of their containing block and sets the width to be that of the column:

img {
  float: bottom;
  width: 1gr;
}

The column box is the containing block for floats, so if an image naturally appears in the first column it will float to its bottom:

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

This code floats figures to the top of the multi-column element.

div.figure {
  float: top right multicol;
  width: 1gr }

The ‘1gr’ value on ‘width’ is equal to the width of the containing block. Here is a possible rendering:

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.

In this code, the ‘float’ property floats the element to the top left of the multi-column element, while the ‘float-offset’ property pushes it to the right so that it ends up in the column next to it:

div.quote {
  float: top left multicol;
  float-offset: 2.5gr;
  width: 1gr }

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Assuming a three-column layout, the same rendering can be achieved by floating the element to the right instead:

div.quote {
  float: top right multicol;
  float-offset: 2gr;
  width: 1gr }

The floated element will never be pushed outside the content edges of the multicol element due to ‘float-offset’.

img {
  float: top right multicol;
  width: 3gr;
}

The code above floats the element to the top right of the multi-column element. Further, it sets the width of images to the width of two columns plus the gap between them. Here is a possible rendering.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.

img {
  float: top right multicol;
  width: 2gr;
}

The code above floats the element to the top right of the multi-column element. Further, it sets the width of the image to the width of one column plus one column gap. Here is a possible rendering.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.

img {
  float: top right multicol;
  width: 1.5gr;
}

The code above floats the element to the top right of the multi-column element. Further, it sets the width of the image to the width of one column plus half the column gap.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.

img {
  float: top left multicol;
  float-offset: 1.5gr 50%;
  width: 8em;
}

The first rule in the code above floats images to the top left of the multi-column element. The second rule pushes the float in the opposite directions: to the right and downwards. The horizontal component (‘1.5gr’) means that the horizontal middle of the element should be in the middle of the gap between the left-most column and the one next to it. Vertically, element should be in the middle of the column. Here is a possible rendering:

Lorem ipsum dolor
sit amet. Nam at jus.
Sed
imp
er di
et ris.
Cur
abi
tur et sapen. Fusce
sed ligula a turpis.

Lorem ipsum dolor
sit amet. Nam at jus.

Sed
imp
er di
et ris.
Cur
abi
tur et sapen. Fusce
sed ligula a turpis.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Consider this code:

img {
  float: top left multicol;
  float-offset: 1.25gr 50%;
  width: 6em;
}

The only difference between this and the previous example is the horizontal value on ‘float-offset’. The value ‘1.25gr’ means that a point 25% into the image in the inline direction will be aligned with a point 25% into the column gap. Here is a possible rendering:

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imper di et
ris. Cur abi tur
et sapen. Fusce
sed ligula a sic
turpis. Lorem
ipsum dolor sit
amet. Namat jus. Sed
imper di et ris curit.

Lorem ipsum dolor
sit amet. Nam at jus.

Sed
imp
er di
et ris.
Cur
abi
tur et sapen. Fusce
sed ligula a turpis.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

15. Conformance

16. Appendix A: Default style sheet

@page {
  counter-reset: footnote;
  @footnote {
    counter-increment: footnote;
    float: page bottom;
    width: 100%;
    height: auto;
  }
}

::footnote-call {
  counter-increment: footnote;
  content: counter(footnote, super-decimal);
}
::footnote-marker {
  content: counter(footnote, super-decimal);
}

h1 { bookmark-level: 1 }
h2 { bookmark-level: 2 }
h3 { bookmark-level: 3 }
h4 { bookmark-level: 4 }
h5 { bookmark-level: 5 }
h6 { bookmark-level: 6 }

Acknowledgments

This document has been improved by Bert Bos, Michael Day, Melinda Grant, David Baron, Markus Mielke, Steve Zilles, Ian Hickson, Elika Etemad, Laurens Holst, Mike Bremford, Allan Sandfeld Jensen, Kelly Miller, Werner Donné, Tarquin (Mark) Wilton-Jones, Michel Fortin, Christian Roth, Brady Duga, Del Merritt, Ladd Van Tol, Tab Atkins Jr., Jacob Grundtvig Refstrup, James Elmore, Ian Tindale, Murakami Shinyu, Paul E. Merrell, Philip Taylor.

References

Normative references

[CSS3LIST]
Ian Hickson; Tantek Çelik. CSS3 module: Lists. 7 November 2002. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2002/WD-css3-lists-20021107
[CSS4BACKGROUND]
Elika J. Etemad; Håkon Wium Lie. CSS Backgrounds and Borders Module Level 4. Proposal for a CSS module. (Retrieved 2 June 2010) URL: http://dev.w3.org/csswg/css4-background/

Other references

[CSS2]
Ian Jacobs; et al. Cascading Style Sheets, level 2 (CSS2) Specification. 11 April 2008. W3C Recommendation. URL: http://www.w3.org/TR/2008/REC-CSS2-20080411
[CSS3COL]
Håkon Wium Lie. CSS Multi-column Layout Module. 17 December 2009. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2009/CR-css3-multicol-20091217
[CSS3PAGE]
Melinda Grant; Håkon Wium Lie. CSS3 Module: Paged Media. 10 October 2006. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2006/WD-css3-page-20061010

Index

  • bleed, 9.
  • bookmark-label, 10.
  • bookmark-level, 10.
  • bookmark-state, 10.
  • bookmark-target, 10.
  • float-offset, 14.1.
  • hyphenate-after, 6.1.
  • hyphenate-before, 6.1.
  • hyphenate-character, 6.1.
  • hyphenate-lines, 6.1.
  • hyphenate-resource, 6.1.
  • hyphens, 6.1.
  • image-resolution, 8.
  • marks, 9.
  • named strings, 2.
  • running elements, 2.
  • string-set, 2.1.1.

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
bleed | <length> | 6pt | page context | no | refer to width of page box | visual
bookmark-label | content() | attr() | <string> | content() | all elements | no | N/A | all
bookmark-level | none | <integer> | none | all elements | no | N/A | all
bookmark-state | open | closed | open | block-level elements | no | N/A | all
bookmark-target | none | <uri> | <attr> | none | all elements | no | N/A | all
float-offset | <length> <length> ? | 0 0 | floated elements | no | refer to width and height of containing block | visual, paged
hyphenate-after | <integer> | auto | auto | all elements | yes | N/A | visual
hyphenate-before | <integer> | auto | auto | all elements | yes | N/A | visual
hyphenate-character | auto | <string> | auto | all elements | yes | N/A | visual
hyphenate-lines | no-limit | <integer> | no-limit | all elements | yes | N/A | visual
hyphenate-resource | none | <uri> [, <uri> ]* | none | all elements | yes | N/A | visual
hyphens | none | manual | auto | manual | all elements | yes | N/A | visual
image-resolution | normal | [ from-image || <dpi> ] | normal | replaced elements and background images? | yes | N/A | visual
marks | [ crop || cross ] | none | none | page context | no | N/A | visual, paged
string-set | [[ <identifier> <content-list>] [, <identifier> <content-list>]* ] | none | none | all elements | no | N/A | all


CSS3 Grid Positioning Module

CSS Grid Positioning Module Level 3

W3C Working Draft 5 September 2007

This version:
http://www.w3.org/TR/2007/WD-css3-grid-20070905
Latest version:
http://www.w3.org/TR/css3-grid
Previous version:
none
Editors:
Alex Mogilevsky, Microsoft, alexmog@microsoft.com
Markus Mielke, Microsoft, mmielke@microsoft.com

Copyright © 2007 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

This module describes integration of grid-based layout (similar to the grids traditionally used in books and newspapers) with CSS sizing and positioning.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css3-grid” in the subject, preferably like this: “[css3-grid] …summary of comment…”

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This is the first public working draft of this module.

Table of contents

  • 1. Dependencies on other modules
  • 2. Introduction
  • 3. Examples
    • 3.1. Example 1
    • 3.2. Example 2
    • 3.3. Example 3
  • 4. Grid declarations
    • 4.1. Explicit grid
      • 4.1.1. ‘grid-columns’ and ‘grid-rows’ properties
    • 4.2. Natural grid
      • 4.2.1. Multi-column element
      • 4.2.2. Table
      • 4.2.3. Priority of explicit grid definition
    • 4.3. Default grid
  • 5. Grid container
  • 6. Grid units
    • 6.1. Applicability of grid units
    • 6.2. Reference point for grid units
    • 6.3. Undefined grid units
  • 7. Grid in overflow
  • 8. Issues
    • 8.1. Snap to grid
    • 8.2. Named grid lines and cells
    • 8.3. Templates in CSS3 Advanced Layout module
  • Acknowledgments
  • References
    • Normative references
    • Other references
  • Index
  • Property index

1. Dependencies on other modules

This CSS3 module depends on the following other CSS3 modules:

  • [CSS3VAL]

It has non-normative (informative) references to the following other CSS3 modules:

  • [CSS3COL]
  • [CSS3GCPM]
  • [MEDIAQ]
  • [CSS3LAYOUT]

2. Introduction

Grid systems have provided great value to print designers for many years [THEGRID]. Now same concepts are applied to online content [SXSWGRIDS], [AGBDL]. Unlike print media however, dimensions of online devices vary broadly; a single fixed-sized grid that worked perfectly for print pages only works in a subset of web scenarios. Really adaptable solutions require dealing with a grid that adapts to fit devices of varying form factors.

This module adds capabilities for sizing and positioning in terms of a scalable grid . The grid can be specified directly by author, or can be implied from existing two-dimensional structures (tables or multi-column elements).

Grid positioning addresses layout in continuous media and in paged media.

Note that the adaptive grid is even more powerful when used in combination with [MEDIAQ].

3. Examples

Let's start with an illustration of grid positioning in action.

3.1. Example 1

example of a 3-column layout with an image that spans 2 columns

Float in a multi-column element

Figure 1 shows a 3-column layout in paged media. It can be seen as a grid with 6 vertical lines and 2 horizontal lines.

We can use the grid lines to position the floating image:

body { columns:3; column-gap:0.5in; }
img { float:page top right; width:3gr; }
/* Figure 1 */

The statement "float:page top right" here positions the image at the top right corner of the page (as defined in [CSS3GCPM])

"width:3gr" makes image 3 "grid units" wide, where a "grid unit" is the distance between two adjacent grid lines. Each boundary between a column and a gap automatically produces a grid line, therefore to specify "two columns, including the gap between columns, but not including any gaps outside the columns" we can just say "3gr".

3.2. Example 2

The previous example addressed grid lines created automatically by multi-column layout (an implicit grid). In more complex pages, base grid of the page is designed in advance, and it is not necessarily used to be filled with content directly. Instead, elements of page content are aligned to the grid.

For this case, grid can be specified explicitly. It is not required (although common) that grid has evenly spaced columns with gaps in between. The grid is simply a collection of horizontal and vertical lines.

example of a multicolumn layout with additional gridlines in the middle of each column

Explicitly specified grid lines

These additional grid lines allow to position elements in ways that would be impossible otherwise:

body { grid-columns: * * (0.5in * *)[2];
       grid-rows: 20% *;
       columns:3; column-gap:0.5in; }

img  { float:page top left;
       float-offset: 4gr 1gr; }

/* Figure 2 */

In this example,

  • An explicit grid is specified
  • Group in parentheses is a repeating pattern
  • Integer in square brackets is the number of repetitions
  • star syntax (as in multi-length [HTML401]) represents a proportional length (each * gets equal space allocation; you can use 2*, 3* etc.)

3.3. Example 3

The following example illustrates the use of a grid in construction of a complex web site. Note how groups of elements are aligned with different sets of grid lines.

[image of a complex page with overlaid grid] [image of complex page]

Complex site designed with a grid

4. Grid declarations

There are three ways to define a grid.

  1. Explicit grid: defined with 'grid-columns', 'grid-rows' properties.
  2. Natural grid: automatically created by elements with a natural grid structure (multi-column elements and tables).
  3. Default grid: all other block elements define a single-cell grid.

4.1. Explicit grid

Outer edges of padding box always define grid lines. In LTR layout, left and top edges define lines that we refer as horizontal and vertical line zero (right and top in RTL). The opposite edges also define grid lines.

Additional grid lines can be added in the middle with ‘grid-columns’ and ‘grid-rows’ properties.

4.1.1. ‘grid-columns’ and ‘grid-rows’ properties

Name: | grid-columns
Value: | [[<length>|<percentage>|<relative length>] | ([<length>|<percentage>|<relative length > ]+)[‘[’<integer>‘]’]? ]+ | none | inherit
Initial: | none
Applies to: | all elements
Inherited: | no
Percentages: | refer to width of containing block
Media: | visual, paged
Computed value: | specified value
Name: | grid-rows
Value: | [[<length>|<percentage>|<relative length>] | ([<length>|<percentage>|<relative length > ]+)[‘[’<integer>‘]’]? ]+ | none | inherit
Initial: | none
Applies to: | all elements
Inherited: | no
Percentages: | refer to height of containing block
Media: | visual, paged
Computed value: | specified value

Space for each column or row of the grid can be defined as

  • Length.
    • Note that gr unit can also be used here (it refers to grid of the containing block)
  • Percentage of containing block height and width
  • Relative length (as defined in multi-length type in [HTML401]):

A relative length has the form "i*", where "i" is an integer. When allotting space among elements competing for that space, user agents allot pixel and percentage lengths first, then divide up remaining available space among relative lengths. Each relative length receives a portion of the available space that is proportional to the integer preceding the "*". The value "*" is equivalent to "1*". Thus, if 60 pixels of space are available after the user agent allots pixel and percentage space, and the competing relative lengths are 1*, 2*, and 3*, the 1* will be allotted 10 pixels, the 2* will be allotted 20 pixels, and the 3* will be allotted 30 pixels.

This definition is taken directly from HTML4.01. But it doesn't have to be exactly same. The number doesn't have to be integer. And maybe the number should be required for consistency with other units.

For example this rule

div { grid-columns: 50% * * 4em }
  • adds one grid line in the middle of containing block,
  • another one 4em from the right
  • another one in the middle of remaining space

Also, grid lines can be defined in repeating groups. A group is enclosed in parentheses and optionally specifies a maximum number of repetitions in square brackets. Nested repeating groups are not allowed.

For example this rule

div { grid-rows: 4em (0.25em 1em); }
  • defines a header row of 4em
  • adds as many additional rows as necessary, alternating heights of 0.25em and 1em.

For another example this rule

div { grid-columns: * (1em *)[2]; }

defines 3 columns of equal widths with 1em gaps, which matches a multi-column layout defined as

div { column-count: 3; }

(assuming 1em is the default value of column gap).

4.2. Natural grid

Elements with a natural grid structure define a grid that aligns with the structure. Such elements are

4.2.1. Multi-column element

POWERED BY HeroNote

Left and right edges of each column form a grid line. There are twice as many grid lines as there are columns.

4.2.2. Table

There is one grid line per row and per column. The line is at the row/column boundary.

A possible alternative is to have two lines per table row/column, on both sides of border-spacing. In collapsing borders model these border lines would also collapse in one.

4.2.3. Priority of explicit grid definition

If explicit grid properties grid-columns or grid-rows are specified on an element with an implicit grid the explicit properties have priority.

4.3. Default grid

Element that does not define an explicit grid and that is not any of elements defining an implicit grid is considered to have a single-cell grid, equivalent to having this explicit definition in default stylesheet:

* { grid-columns:*; grid-rows:*; }

5. Grid container

Using grid does not require any new rules on how the positioning container is determined. When grid units are used with all applicable sizing positioning methods, the grid is always taken from the applicable containing block (which is found as defined as defined in CSS2.1 section 10.1).

In this example, div1 is the positioning parent and therefore grid of div1 is used for positioning:

<style>
 .div1 { position:absolute; grid-columns:4.5em (1em 4.5em); } /* this grid is used */
 .div2 { columns-width:10em; column-gap:1em; }
 img { position:absolute; left:2gr; width:3gr; }
</style>
<div class="div1">
 <div class="div2">
  <img />
 </div>
</div>

However in the next example, grid of div2 is used by the float, because it is the float's containing block:

<style>
 .div1 { position:absolute; grid-columns:4.5em (1em 4.5em); }
 .div2 { columns-width:10em; column-gap:1em; } /* this grid is used */
 img { float:left; float-offset:2gr; width:3gr; }
</style>
<div class="div1">
  <div class="div2">
   <img />
  </div>
</div>

6. Grid units

‘gr’ is used to position in relation to the grid lines. Actual value of each gr depends on the grid cell in which it is used.

Example

div { columns:3; }
div img { float: top left column;
          float-offset: 2gr;
          width: 1gr }

The image is positioned over the 2nd column (left edge of second column is 2nd grid line from left; its width is the distance to the next grid line).

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Fractions of gr unit can be used too. In this example

div img { float:column; float-offset: 0.5gr; width: 2gr; }

the image takes exactly the width required to stretch from the middle of first column to the middle of second column. width:2gr in the example doesn't start from exactly a grid line, therefore it is calculated as a sum of grid parts (2gr = 0.5gr + 1gr + 0.5gr), which ends in the middle of second column.

Lorem ipsum dolor sit amet. Nam at jus. Sed imp er di et ris. Cur abi tur et sapen. Fusce sed ligula a turpis. Vivamus a metus.

Lorem ipsum dolor sit amet. Nam jus.
Sed imp er di et ris. Cur abi tur et sapen. Fusce sed ligula a turpis.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

6.1. Applicability of grid units

Grid units are applicable to all properties of block elements that take values of type <length>.

When applied to margins, borders and padding, grid units refer to grid lines in the direction of line progression (horizontal in layout with horizontal lines).

Grid units never apply to inline elements, including inline blocks.

6.2. Reference point for grid units

ISSUE: Calculating grid units require a reference point within the grid and direction. This needs a precise definition. For the same element, grid units for position and size may have different reference points (but probably not different directions).

6.3. Undefined grid units

Because of positional nature of 'gr' unit it is ambiguous in absence of position. Also, grid size may not be defined when a grid unit has to be applied.

In such case values specified in 'gr' units are ignored (set to their initial value).

Need some examples here. E.g. what happens to '1gr' float in a multi-column element within a table that is sized to content? Grid size depends on the float's size so 'gr' should be ignored.

7. Grid in overflow

When a measure defined in grid units extends outside the boundaries of grid container, grid lines are repeated according to the following rules

  • If overflow is in positive direction (right/bottom in left-to-right/top-to-bottom flow, direction of text and block progression in other flows)
    • Explicit grid
      • If the grid definition ends with a repeat pattern (regardless of repeat count), the same pattern continues indefinitely
      • Otherwise, the last column or row size is repeated
    • Default grid
      • Same as non-repeating pattern: equally spaced lines are added, separated by the size of the element
    • Multi-column element
      • Additional (gap, column) pairs are added.
        • Current definition of multi-column layout doesn't allow variable-width columns; when it does, the last column with the last column gap should be repeated
    • Table
      • The last column is repeated
  • If overflow is in negative direction
    • The same sequence is used as in positive direction, but mirrored.

TODO: example

8. Issues

8.1. Snap to grid

Should there be an option to align flow content to next available gridline? It opens really cool scenarios. But are they compelling enough to create a next available notion?

8.2. Named grid lines and cells

If grid is used extensively, named grid locations would be quite helpful. Defining named grid lines could look for example like this:

body { grid-columns: "left-edge" * 1em * 0.5em "center" 0.5em * 1em * "right-edge";

But this syntax doesn't easily extend to named cells

8.3. Templates in CSS3 Advanced Layout module

"Template-based positioning" in CSS3 Advanced Layout module [CSS3LAYOUT] defines scalable templates for content to fill and also used the term "grid".

The relationship between these modules certainly needs to be well defined.

Note that technically these modules are not contradictory (as long as is defined how an advanced-layout template produces an implicit grid).

Acknowledgments

This specification is made possible by input from Håkon Wium Lie, Steve Zilles, Mike Duggan, Bill Hill, Geraldine Wade, [to be added].

Thanks to Khoi Vinh for the “Yeeaahh!” Example.

References

Normative references

[CSS3VAL]
Håkon Wium Lie; Chris Lilley. CSS3 module: Values and Units. 19 September 2006. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2006/WD-css3-values-20060919
[HTML401]
David Raggett; Arnaud Le Hors; Ian Jacobs. HTML 4.01 Specification. 24 December 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-html401-19991224

Other references

[AGBDL]
Charles Jacobs; et al. "Adaptive Grid Based Document Layout" in: ACM Transactions on Graphics. 22. 3. pp. 838–847. July 2003. URL: http://grail.cs.washington.edu/pub/papers/Jacobs2003.pdf
[CSS3COL]
Håkon Wium Lie. Multi-column layout in CSS. 6 June 2007. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2007/WD-css3-multicol-20070606
[CSS3GCPM]
Håkon Wium Lie. CSS Generated Content for Paged Media Module. 4 May 2007. W3C Working Draft. (Work in progress) URL: http://www.w3.org/TR/2007/WD-css3-gcpm-20070504
[CSS3LAYOUT]
Bert Bos. CSS3 Advanced Layout Module. 9 August 2007. W3C Working Draft. (Work in progress) URL: http://www.w3.org/TR/2007/WD-css3-layout-20070809
[MEDIAQ]
Håkon Wium Lie; Tantek Çelik; Daniel Glazman. Media Queries. 6 June 2007. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2007/CR-css3-mediaqueries-20070606
[SXSWGRIDS]
Khoi Vinh; Mark Boulton. Grids Are Good. March 2007. SXSW Interactive, Austin, TX. URL: http://www.subtraction.com/pics/0703/grids_are_good.pdf
[THEGRID]
Allen Hurlburt. Grid: A Modular System for the Design and Production of Newpapers, Magazines, and Books. 1982. ISBN 0-471-28923-X.

Index

  • grid-columns, #
  • grid-rows, #

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
grid-columns | [[<length>|<percentage>|<relative length>] | ([<length>|<percentage>|<relative length > ]+)[‘[’<integer>‘]’]? ]+ | none | inherit | none | all elements | no | refer to width of containing block | visual, paged
grid-rows | [[<length>|<percentage>|<relative length>] | ([<length>|<percentage>|<relative length > ]+)[‘[’<integer>‘]’]? ]+ | none | inherit | none | all elements | no | refer to height of containing block | visual, paged


CSS3 Hyperlink Presentation Module

W3C Working Draft 24 February 2004

This version:
http://www.w3.org/TR/2004/WD-css3-hyperlinks-20040224
Latest version:
http://www.w3.org/TR/css3-hyperlinks
Previous version:
none
Editors:
Tantek Çelik <tantekc @microsoft.com>
Bert Bos <bert @w3.org>
Daniel Glazman <danielglazman @easyconnect.fr>

Copyright © 2004 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.

Abstract

This is the first draft of the CSS3 Hyperlink Presentation Module. It is published to get some early feedback. The properties in it and even the scope of the draft are still very unstable. The draft may be dropped or merged with another.

CSS (Cascading Style Sheets) is a simple language for describing the presentation of documents. This specification is a module of level 3 of CSS and contains the functionality required to describe the presentation of hyperlink source anchors and the effects of hyperlink activation.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede it. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress." Its publication does not imply endorsement by the W3C membership. Implementations for the purpose of experimenting with the specification are welcomed, as long as they are clearly marked as experimental.

This document is a working draft of the CSS Working Group which is part of the style activity (see summary).

Comments on and discussions of this draft can be sent to the (archived) public mailing list www-style@w3.org (see instructions). W3C Members can also send comments directly to the CSS working group.

Patent disclosures relevant to CSS may be found on the Working Group's public patent disclosure page.

This is the first draft in this series ("css3-hyperlinks").

Table of contents

  • 1. Dependencies
  • 2. Requirements and principles
    • 2.1. Open Issues
  • 3. Target properties
    • 3.1. Property summary
    • 3.2. The 'target-name' property
    • 3.3. The 'target-new' property
    • 3.4. The 'target-position' property
    • 3.5. The 'target' property
  • 4. Conformance
  • Acknowledgments
  • References
    • Normative references
    • Other references
  • Default style sheet
  • Index
  • Property index

1. Dependencies

This CSS3 module depends on the following other CSS specification(s):

  • CSS2.1 [CSS21]

It has non-normative (informative) references to the following other CSS3 modules:

  • Selectors[[SELECTORS]]
  • CSS3 Basic User Interface Module [CSS3UI]
  • CSS3 Generated and Replaced Content Module [CSS3GENCON]

2. Requirements and principles

A hyperlink is a combination of a link with the semantic of an external reference, something which is considered outside the content document. This is in contrast to an embed, which is a link with the semantic of an internal reference, something which is considered a part of the document (such as an embedded image). There are also local hyperlinks which simply point to navigation points (anchors) in the current document.

A hyperlink is a combination of a link with a certain behavior: it is a link that is presented in such a way that the user recognizes it as something he can activate quickly and easily (with a mouse click, key press, etc.), and which, on activation causes the target reference of the link to be retrieved and displayed to the user, shortly after activation.

The scope of this CSS module can be summarized with the following list of principles:

  1. Linking semantics and link presentation are separable [TAGLINK20030116]. The task of CSS is presentation.
  2. The aspects of a hyperlink that differ depending on device, platform or user accessibilty [WCAG] requirements are likely to be presentational [TAGLINK20030116].
  3. The presentation of a document should normally be specified separately from its content, and preferably in a CSS style sheet.
  4. Some parts of behavior are presentational; e.g., CSS can say that activation of a hyperlink causes a new window to pop up (but not, e.g., that the activation sends a POST request to a server). The specifiable behaviors include:
    • replace current document or portion of a document by target
    • pop up a temporary window (possibly modal) with the target
    • ditto, but pop "under"
    • show target in a specific window
    • using tabs in a tabbed interface rather than windows in the above
  5. CSS is also able to suppress all behavior, thus making it impossible to activate a hyperlink. UAs should always allow the user to disable particular style sheets.
  6. CSS can be used to describe a large class of common hyperlink styles, but not all possible styles.
  7. CSS doesn't rely on specific mark-up in a source document, but is able to style hyperlinks in many different document formats. In particular, it can style HTML [HTML401] and XHTML [XHTML10] documents, documents that use HLink [HLINK], a large part of XML [XML10] documents that use XLink [XLINK10], e.g. SVG [SVG10] and several others.
  8. The boundary between semantics and style is not sharp. For ease of use, CSS sometimes has to allow some aspects of semantics to be expressed in CSS. E.g., CSS style rules may say which attribute of an element that has several is used for the hyperlink. (But CSS is not able to say, e.g., what base to use to resolve relative URLs [RFC1808].)
  9. The previous point notwithstanding, CSS assumes that, in general, the UA has knowledge about the document format from other sources (or hardcoded) and classifies elements as hyperlinks or not. E.g., the CSS pseudo-classes ':link' and ':visited' match only elements that are hyperlinks.

This module does not deal with

  1. Replaced elements, i.e. embeds.
  2. Footnotes.
  3. Event bindings.

Even though replaced elements are represented in many mark-up languages in ways that are syntactically similar to hyperlinks (often an element with an attribute that holds a URI [URI] reference), in terms of both semantics, and typically presentation, they are different. Replaced elements are defined in the CSS3 Content module [CSS3GENCON].

Footnotes often serve similar purposes as hyperlinks, but in non-interactive documents.

Activation of a hyperlink needs an action (event) by the user, e.g., a key press or a mouse click. This module does not define what events activate which links. Some such UI issues (not only for hyperlinks) are dealt with in the CSS3 Basic UI module [CSS3UI].

2.1. Open Issues

The following open issues have been recognized, and are documented here for the purpose of discussion. All issues MUST be resolved before CR.

  • How are secondary (or even tertiary) links styled? Do they need to be? Or should their interactivity be left up to the user agent?

3. Target properties

These properties specify where the target of a hyperlink is displayed, after activation of the hyperlink. Not all UAs support all values.

3.1. Property summary

  • target-name: current | root | parent | new | modal | <string>
  • target-new: window | tab | none
  • target-position: above | behind | front | back
  • target: <target-name> || <target-new> || <target-position>

3.2. The 'target-name' property

The 'target-name' property defines the name of the target destination, including a few keywords for well known destinations.

Name: | target-name
Value: | current | root | parent | new | modal | <string>
Initial: | current
Applies to: | hyperlinks
Inherited: | no
Percentages: | N/A
Media Group(s): | interactive visual
Computed value: | specified value

POWERED BY HeroNote

The values mean the following:

current
The name of the current frame, tab or window where the link resides. This value never causes a new destination to be created.
root
The name of the current tab (if there is one) or window. This value never causes a new destination to be created.
parent
The name of the parent of the current frame. If the current frame has no parent this value is treated as 'root'. This value never causes a new destination to be created.
new
A new destination (see 'target-new') is always created.
modal
A new modal window is temporarily created.
<string>
The target is displayed in the existing frame, window or tab of that name. If no such named destination exists, a new destination (see 'target-new') is created with that name.

3.3. The 'target-new' property

The 'target-new' property determines what new target destination (if any) is created.

Name: | target-new
Value: | window | tab | none
Initial: | window
Applies to: | hyperlinks
Inherited: | no
Percentages: | N/A
Media Group(s): | interactive visual
Computed value: | specified value
window
The target is displayed in a new window.
tab
The target is displayed in a new tab of an existing window.
none
No new destination is created. The target is not displayed.

If a user wanted to have new windows open in new tabs instead, she could use the following user style sheet to do so:

* { target-new: tab ! important }

3.4. The 'target-position' property

The 'target-position' property indicates where a new destination (if any) is created.

Name: | target-position
Value: | above | behind | front | back
Initial: | above
Applies to: | hyperlinks
Inherited: | no
Percentages: | N/A
Media Group(s): | interactive visual
Computed value: | specified value
above
The new destination tab (window) is placed above the current tab (window) respectively.
behind
The new destination tab (window) is placed behind the current tab (window) respectively.
front
The new destination tab (window) is placed above all other tabs (windows) respectively.
back
The new destination tab (window) is placed behind all other tabs (windows) respectively.

Both 'target-position' and 'target-new' only apply if due to the value of 'target-name', a new tab (or window) is being created. Neither 'target-position' nor 'target-new' can actually cause a new destination to be created. They just determine what is created and where.

3.5. The 'target' property

Name: | target
Value: | <target-name> || <target-new> || <target-position>
Initial: | see individual properties
Applies to: | hyperlinks
Inherited: | no
Percentages: | N/A
Media Group(s): | interactive visual
Computed value: | see individual properties

The 'target' property is a shorthand property for setting the individual target properties (i.e., 'target-name', 'target-new' and 'target-position') at the same place in the style sheet.

Given a valid declaration, the 'target' property first sets all the individual target properties to their initial values, then assigns explicit values given in the declaration.

4. Conformance

There will be a test suite.

Acknowledgments

[acknowledgments]

References

Normative references

[CSS21]
Bert Bos; Tantek Çelik; Ian Hickson; Håkon Wium Lie. Cascading Style Sheets, level 2 revision 1. 15 September 2003. W3C Working Draft. (Work in progress) URL: http://www.w3.org/TR/2003/WD-CSS21-20030915
[CSS3SYN]
David Baron. CSS3 module: syntax. (forthcoming). W3C working draft. (Work in progress.)
[CSS3VAL]
Håkon Wium Lie; Chris Lilley. CSS3 Values and Units Module. 13 Jul 2003. W3C working draft. (Work in progress.) URL: http://www.w3.org/TR/2001/WD-css3-values-20010713

Other references

[CSS3GENCON]
Håkon Wium Lie; Ian Hickson. CSS3 module: generated text. (forthcoming). W3C working draft. (Work in progress.)
[CSS3UI]
Tantek Çelik. CSS3 Basic User Interface Module. 3 Jul 2003. W3C working draft. (Work in progress.) URL: http://www.w3.org/TR/2003/WD-css3-ui-20030703
[HLINK]
Steven Pemberton; Masayasu Ishikawa. Link recognition for the XHTML Family. 2002. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2002/WD-hlink-20020913/
[HTML401]
Raggett, D.; Le Hors, A.; Jacobs, I.. HTML 4.01 Specification. Dec 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-html401-19991224
[RFC1808]
R. Fielding. Relative Uniform Resource Locators. June 1995. Internet RFC 1808. URL: http://www.ietf.org/rfc/rfc1808.txt
[SVG10]
Various. Scalable Vector Graphics (SVG) 1.0 Specification. Sep 2001. W3C Recommendation. URL: http://www.w3.org/TR/2001/REC-SVG-20010904
[TAGLINK20030116]
Ian Jacobs (Scribe). Minutes of 16 Jan 2003 discussion on Linking in XML Documents. 2003. W3C TAG archives. URL: http://www.w3.org/2003/01/16-tag-xlink
[URI]
T. Berners-Lee; R. Fielding; L. Masinter. Uniform Resource Identifiers (URI): generic syntax. August 1998. Internet RFC 2396. URL: http://www.isi.edu/in-notes/rfc2396.txt
[WCAG]
Wendy Chisholm; Gregg Vanderheiden; Ian Jacobs. Web Content Accessibility Guidelines 1.0. 5-May-1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/WAI-WEBCONTENT-19990505
[XHTML10]
Steven Pemberton; et al. XHTML 1.0: The Extensible HyperText Markup Language. Jan 2000. W3C Recommendation. URL: http://www.w3.org/TR/2000/REC-xhtml1-20000126
[XLINK10]
DeRose, Steve; Maler, Eve; Orchard, David. XML Linking Language (XLink) Version 1.0. Jun 2001. W3C Recommendation. URL: http://www.w3.org/TR/2001/REC-xlink-20010627
[XML10]
Tim Bray; Jean Paoli; C. M. Sperberg-McQueen; Eve Maler. Extensible Markup Language (XML) 1.0 (Second Edition). Oct 2000. W3C Recommendation. URL: http://www.w3.org/TR/2000/REC-xml-20001006

Default style sheet

This section is informative, only provides a few example rules, and is not intended to comprehensively describe the HTML4/XHTML/XLink "target" behaviors.

@namespace xlink url(http://www.w3.org/1999/xlink);

a[target],
area[target],
form[target]
  { target: attr(target,string) }

a[target="_blank"],
area[target="_blank"],
form[target="_blank"]
  { target: new }

a[target="_self"],
area[target="_self"],
form[target="_self"]
  { target: current }

a[target="_parent"],
area[target="_parent"],
form[target="_parent"]
  { target: parent }

a[target="_top"],
area[target="_top"],
form[target="_top"]
  { target: root }

*[xlink|show="new"]
  { target-name: new }

*[xlink|show="replace"]
  { target-name: current }

Index

  • target, #
  • target-name, #
  • target-new, #
  • target-position, #

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
target | <target-name> || <target-new> || <target-position> | see individual properties | hyperlinks | no | N/A | interactive visual
target-name | current | root | parent | new | modal | <string> | current | hyperlinks | no | N/A | interactive visual
target-new | window | tab | none | window | hyperlinks | no | N/A | interactive visual
target-position | above | behind | front | back | above | hyperlinks | no | N/A | interactive visual


CSS3 Image Values Module

CSS Image Values Module Level 3

W3C Working Draft 23 July 2009

This version:
http://www.w3.org/TR/2009/WD-css3-images-20090723/
Latest version:
http://www.w3.org/TR/css3-images/
Previous version:
-
Editor:
Elika J. Etemad

Copyright © 2009 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

This CSS Image Values module defines the syntax for <image> values in CSS. <image> values can be a single URI to an image, a list of URIs denoting a series of fallbacks, sprites (image slices), or gradients.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css3-images” in the subject, preferably like this: “[css3-images] …summary of comment…”

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This is the first public working draft in the “css3-images” series.

Table of contents

  • 1 Introduction
  • 2 Conformance
  • 3 The <image> value type
  • 4 Image References and Image Slices: the ‘url()’ notation
  • 5 Image Fallbacks: the ‘image()’ notation
  • 6 Image Sprites
  • 7 Resolution Units
  • Acknowledgments
  • References
    • Normative references
    • Informative references

1 Introduction

This section is non-normative.

In CSS Levels 1 and 2, image values, such as those used in the ‘background-image’ property, could only be given by a single URI value. This module introduces additional notations that allow a 2D image to be given as a list of URIs denoting fallbacks, as a slice of a larger image (sprite), and as a gradient.

2 Conformance

A document or implementation cannot conform to CSS Image Values Level 3 alone, but can claim conformance to CSS Image Values Level 3 if it satisfies the conformance requirements in this specification when implementing CSS or another host language that normatively references this specification.

Conformance to CSS Namespaces is defined for two classes:

style sheet
A CSS style sheet (or a complete unit of another host language that normatively references CSS Namespaces).
interpreter
Someone or something that interprets the semantics of a style sheet. (CSS user agents fall under this category.)

The conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification. All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words "for example" or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word "Note" and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

POWERED BY HeroNote

3 The <image> value type

The <image> value type denotes a 2D image. It is defined as

<image> = <url> | <sprite> | <image-list>

Image values can be used in many CSS properties, including the ‘background-image’, ‘list-style-image’, ‘cursor’ properties [CSS21].

4 Image References and Image Slices: the ‘url()’ notation

The simplest way to indicate an image is to reference an image file by URI. This is done with the ‘url()’ notation, defined in [CSS21].

In the example below, a background image is specified with ‘url()’ syntax:

background-image: url(wavy.png);

A portion of an image may be referenced (clipped out and used as a standalone image) by use of fragment identifiers. Need a spec to reference here. Expecting to get one from Media Fragments WG.

For example,

background-image: url('logos.png#xywh=10,30,60,20')

uses the 60 pixel by 20 pixel rectangle of logos.png beginning at the point 10 pixels in from the left, 30 pixels down from the top.

Note that quotation marks are required here, because unquoted commas are not allowed in ‘url()’ syntax.

5 Image Fallbacks: the ‘image()’ notation

The ‘image()’ notation allows an author to specify multiple images, each one a fallback for the previous. The UA must use only the first image that it can load and display. The syntax for ‘image()’ is defined as

<image-list> = image( [ <image-decl> , ]* [ <image-decl> ] [ or <color> ]? )

where <image-decl> is given by

<image-decl> = [ <string> | <url-token> ] [ snap? && <resolution> ]?

<url-token> is given as [!#$%&*-~]|{nonascii}|{escape} (i.e. the contents of ‘url()’) using the productions in the CSS2.1 tokenization. The <url-token> must not contain unescaped brackets, commas, white space characters, single quotes (') or double quotes ("); if it does the ‘image()’ containing it is invalid.

Each string or url-token represents the URI of an image. If a resolution is given, then the image must be rendered at the specified resolution. If the ‘snap’ keyword is also specified, and the image is a raster image, then the image must be rendered at the resolution closest to the specified resolution that would result in no pixel rounding. I don't think "no pixel rounding" is the right terminology here... basically we want to avoid blurry images.

The optional color at the end of the list is the fallback color. It is used if, and only if, none of the images can be loaded and displayed (e.g. because they are in unsupported formats, or cannot be found, or are corrupted in some way, or because image loading is disabled in the UA). It is treated as a single-color image with no intrinsic dimensions.

For example, the rule below would tell the UA to load ‘wavy.svg’ if it can; failing that to load ‘wavy.png’ and display it at 150dpi; failing that to display ‘wavy.gif’; and finally, if none of the images can be loaded and displayed, to use the color ‘blue’ to create a dimensionless background image.

background-image: image(wavy.svg, 'wavy.png' 150dpi, "wavy.gif"  or blue);

The ‘background-image’ property specifies that dimensionless images must stretch to cover the entire background positioning area [CSS3BG], so if none of the specified images can be displayed the background will be painted blue. As with any image, this fallback will be painted over the ‘background-color’ (if any).

If the URL for the image ends in a file extension (a period followed by letters) of four ascii letters ([a-zA-Z]) or less, then the UA may skip trying to load images whose file extension matches an image format it knows it does not support. For example, a UA that knows it supports JPEG and GIF, but expects to encounter many PNG and SVG images may choose to skip over images with filenames ending in ‘.png’ or ‘.svg’ without loading them to check their MIME type. However it must not skip over images with filenames ending in extensions it doesn't recognize.

6 Image Sprites

The image sprites syntax is different from image slices noted above. Image slice syntax allows you to specify the coordinates of a region in the image and use that as a standalone image, but all the coordinates must be specified inline. This is great for one-off cutouts, but becomes unnecessarily verbose when the slices fit into a grid structure. The goal of this section is to define a syntax that:

  • Makes it easy to specify an image slice and swap it out in later subclass or :hover rules.
  • Makes it easy to maintain a sprite image, so that adding or shifting sections of the image don't require crawling through and modifying the entire style sheet.
  • Has straightforward handling of strict grids, but can also handle more irregular sprite organization.
  • (Any other use cases/requirements?)

As yet unwritten. Discussions/proposals include:

  • Jorrit's @sprite proposal
  • Adrian's image-vars proposal
  • Discussion from Jan 2008 and Jorrit's response

7 Resolution Units

This specification defines the following units as part of the <resolution> value type:

dpi
dots per inch
dpcm
dots per centimeter
dppx
dots per ‘px’ unit

The default resolution of raster images in CSS is ‘1dppx’.

Acknowledgments

References

Normative references

[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 23 April 2009. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2009/CR-CSS2-20090423/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt

Informative references

[CSS3BG]
Elika J. Etemad; Bert Bos. CSS Backgrounds and Borders Module Level 3. 10 September 2008. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2008/WD-css3-background-20080910


CSS3 Marquee Module

CSS Marquee Module Level 3

W3C Candidate Recommendation 5 December 2008

This version:
http://www.w3.org/TR/2008/CR-css3-marquee-20081205
Latest version:
http://www.w3.org/TR/css3-marquee
Previous version:
http://www.w3.org/TR/2008/WD-css3-marquee-20080801
Editors:
Bert Bos (W3C) <bert@w3.org>

Copyright © 2008 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

CSS describes the rendering of documents on various media. When documents (e.g., HTML) are laid out on visual media (e.g., screen or print) and the contents of some element are too large for a given area, CSS allows the designer to specify whether and how the overflow is displayed. One way, available on certain devices, is the “marquee” effect: the content is animated and moves automatically back and forth. This module defines the properties to control that effect.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document was produced by the CSS Working Group as a Candidate Recommendation.

A Candidate Recommendation is a document that has been widely reviewed and ready for implementation. W3C encourages everybody to implement this specification and return comments to the (archived) public mailing list www-style@w3.org (see instructions). When sending e-mail, please put the text “css3-marquee” in the subject, preferably like this: “[css3-marquee] …summary of comment…”

Publication as a Candidate Recommendation does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

For this specification to exit CR, a minimum of six months must have elapsed, i.e., it will not become Proposed Recommendation before 5 June 2009.

Furthermore, there must be at least two independent, interoperable implementations of each feature. Each feature may be implemented by a different set of products, there is no requirement that all features be implemented by a single product. For the purposes of this criterion, we define the following terms:

independent
each implementation must be developed by a different party and cannot share, reuse, or derive from code used by another qualifying implementation. Sections of code that have no bearing on the implementation of this specification are exempt from this requirement.
interoperable
passing the respective test case(s) in the official CSS test suite, or, if the implementation is not a Web browser, an equivalent test. Every relevant test in the test suite should have an equivalent test created if such a user agent (UA) is to be used to claim interoperability. In addition if such a UA is to be used to claim interoperability, then there must one or more additional UAs which can also pass those equivalent tests in the same way for the purpose of interoperability. The equivalent tests must be made publicly available for the purposes of peer review.
implementation
a user agent which:
  1. implements the specification.
  2. is available to the general public. The implementation may be a shipping product or other publicly available version (i.e., beta version, preview release, or “nightly build”). Non-shipping product releases must have implemented the feature(s) for a period of at least one month in order to demonstrate stability.
  3. is not experimental (i.e. a version specifically designed to pass the test suite and is not intended for normal usage going forward).

This specification only defines the marquee effect for level 2 of the CSS box model, i.e., for horizontal text only, as defined by CSS level 2 [CSS21]. It is expected that this specification will be updated and generalized to include vertical text, once the CSS Text Layout module [CSS3TEXTLAYOUT] is stable.

Table of contents

  • 1. Dependencies on other modules
  • 2. Introduction
  • 3. How to read this specification
  • 4. Terminology
  • 5. The ‘overflow-style’ property
  • 6. The ‘marquee-style’ property
  • 7. The ‘marquee-play-count’ property
  • 8. The ‘marquee-direction’ property
  • 9. The ‘marquee-speed’ property
  • 10. Conformance
  • 11. Acknowledgments
  • 12. Changes
  • References
  • Index
  • Property index

1. Dependencies on other modules

This CSS module depends on the following other CSS modules:

  • Cascading Style Sheets Level 2 Revision 1 [CSS21] for the properties overflow, display, width, margin-left, margin-right, and direction.

2. Introduction

(This section is not normative.)

The marquee effect consists of the UA slowly moving the content of a box so that, over time, all parts of the box are visible at least once. The speed of the movement, whether the movement is in one direction only or back and forth, how far the content moves and how often may vary. But, unlike for most other scrolling mechanisms, the scrolling does not depend on user events. Typically, marquee is used in contexts where there is no room for a scrollbar or other visible mechanism or when user interaction is limited: instead of actively moving hidden content into view, the user waits while the content moves by.

The following rules put the contents of each list item on a single line (unless it has hard line breaks) and causes the list items that are too wide to use a marquee effect (on UAs that support marquee):

li {overflow: auto; overflow-style: marquee-line; white-space: nowrap}

3. How to read this specification

All sections are normative, unless stated otherwise.

Examples look like this and normally start with the word “Example.” Examples are not normative.

Notes look like this and normally start with the word “Note.” Notes are not normative.

Each property is defined in part in the text and in part by a table that groups together a number of facts about the property, including a regular expression to restrict its syntax. See section 1.4.2 of CSS 2.1 [CSS21] for the meaning. The “Inherited” and “Initial” rows in the table are used by the Cascading and Inheritance module [CSS3CASCADE] and “Media” by the Media Queries specification [MEDIAQ].

4. Terminology

A glossary of technical terms (UA, used value, style sheet, element, etc.) can be found in chapter 3 of CSS level 2 [CSS21]. The specification may refer to the specified value, the used value and the computed value of a property as defined in CSS 2.1 [CSS21]. Unless stated explicitly, the short form “value” means the computed value.

5. The ‘overflow-style’ property

Name: | overflow-style
Value: | auto | marquee-line | marquee-block
Initial: | auto
Applies to: | same as ‘overflow’
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | as specified

This property specifies the preferred scrolling method for elements that overflow (see the ‘overflow’ property.) If the UA does not support the specified value, it must act as if the value was ‘auto’.

auto
The UA chooses the scrolling mechanism. Marquees and scrollbars are common mechanisms, but the UA may also use others.
marquee-line
This selects marquee as the horizontal scrolling mechanism (i.e., for content that overflows to the left or right). The scrolling mechanism in the perpendicular direction is left to the UA, but should not be marquee.
marquee-block
This selects marquee as the vertical scrolling mechanism (i.e., for content that overflows above or below the box). The scrolling mechanism in the perpendicular direction is left to the UA, but should not be marquee.

6. The ‘marquee-style’ property

Name: | marquee-style
Value: | scroll | slide | alternate
Initial: | scroll
Applies to: | same as ‘overflow’
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified

The values are:

scroll

Start completely off one side, scroll all the way across and completely off. The following pseudo-code defines the behavior when the marquee direction is to the left (see ‘marquee-direction’). The other directions are analogous.

  1. Set the element to clip the overflow to the left and to the right
  2. Create an anonymous box B around the content; set its ‘width’ so as to include all content and all overflow exactly; set its ‘margin-right’ to ‘auto’
  3. Set n to the value of ‘marquee-play-count’
  4. While n ≠ 0:
    1. Set ‘margin-left’ of B to 100% (i.e., all contents is off to the right and thus invisible)
    2. Decrease ‘margin-left’ at constant speed (see ‘marquee-speed’) until ‘margin-right’ is 100% (i.e., all content is off to the left and thus invisible)
    3. Decrease n by one
slide

Start completely off one side, scroll in, and stop as soon as no more content is off that side. The following pseudo-code defines the behavior when the marquee direction is to the left (see ‘marquee-direction’). The other directions are analogous.

  1. Set the element to clip the overflow to the left and to the right
  2. Create an anonymous box B around the content; set its ‘width’ so as to include all content and all overflow exactly; set its ‘margin-right’ to ‘auto’
  3. Set n to the value of ‘marquee-play-count’
  4. While n ≠ 0:
    1. Set ‘margin-left’ of B to 100% (i.e., all contents is off to the right and thus invisible)
    2. Decrease ‘margin-left’ at constant speed (see ‘marquee-speed’) until ‘margin-right’ is 0
    3. Decrease n by one
alternate

Bounce back and forth. The following pseudo-code defines the behavior when the initial marquee direction is to the left (see ‘marquee-direction’). The other directions are analogous.

  1. Set the element to clip the overflow to the left and to the right
  2. Create an anonymous box B around the content; set its ‘width’ so as to include all content and all overflow exactly
  3. Set r to false
  4. Set n to the value of ‘marquee-play-count’
  5. While n ≠ 0:
    1. If r, set ‘margin-right’ of B to 0 and ‘margin-left’ to ‘auto’; else, set ‘margin-left’ of B to 0 and ‘margin-right’ to ‘auto’
    2. If r, decrease ‘margin-right’ at constant speed (see ‘marquee-speed’) until ‘margin-left’ is 0; else, decrease ‘margin-left’ at constant speed until ‘margin-right’ is 0
    3. Set r to ¬r (i.e., the next loop will move in the opposite direction)
    4. Decrease n by one

Three images: content to the right of a box, content overlapping the box, content to the left of the box.

This figure shows one loop of ‘marquee-style: scroll’. The initial state (1) has all content outside the box to the right. (2) shows an intermediate state. And the final state (3) has all content outside the box on the left.

Three images: content to the right of a box; some content in the box and some to the right; the right edge of the content is just inside the right edge of the box.

This figure shows one loop of ‘marquee-style: slide’. The initial state (1) has all content outside the box to the right. (2) shows an intermediate state. And the final state (3) has the right edge of the content just inside the right edge of the box and some content overflowing to the left of the box.

POWERED BY HeroNote

Five images: content overflows a box only on the right; content overflows on both sides; content overflows only on the left; content overflows on both sides; content overflows only on the right.

This figure show two loops of ‘marquee-style: alternate’. The initial state (1) has the left edge of the content aligned to the left edge of the box and content overflowing on the right. (2) shows an intermediate state, while the content moves to the left. The end of the first loop is state (3). (4) is an intermediate state of the second loop. (5) is the end of the second loop and is equal to state (1).

When the algorithm stops (n = 0), the rendering is left in the state as described. The content is not reset to its initial position. The exception is when ‘marquee-play-count’ is ‘0’. In that case, no looping occurs but the rendering is as it would have been after 2 loops.

The content of an element moves as one piece. E.g., if an element has two lines of text, both lines scroll together, even if only one of them overflows.

7. The ‘marquee-play-count’ property

Name: | marquee-play-count
Value: | <non-negative-integer> | infinite
Initial: | 1
Applies to: | same as ‘overflow’
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified

This property specifies how many times the content moves. UAs should restart the loop count every time the element turns from completely invisible into (fully or partially) visible. E.g., an element that is outside the viewport starts moving when it is scrolled into view.

A UA may also take the visibility of the UA viewport itself into account, e.g., if the element is hidden behind a pop-up window or if the UA is iconified.

If ‘marquee-play-count’ is different for different states of the element, e.g., ‘p {marquee-play-count: 0} p:hover {marquee-play-count: infinite}’, the loop counter must be reset each time the element enters a state with a different computed value.

For example, if the content of an li overflows under the following style rules, the content moves once when the li gets the focus or is hovered over. But, when it already has the focus when it is hovered over, the ‘marquee-play-count’ property doesn't change and thus the content doesn't move again:

li {overflow: auto; overflow-style: marquee; marquee-play-count: 0}
li:focus, li:hover {marquee-play-count: 1}

If the specified value is ‘infinite’ or greater than 16, the UA may stop after 16 loops.

8. The ‘marquee-direction’ property

Name: | marquee-direction
Value: | forward | reverse
Initial: | forward
Applies to: | same as ‘overflow’
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | as specified

This property determines the initial direction in which the content moves if the marquee effect is used. ‘Forward’ moves the text so that hidden text appears in the normal reading order, ‘reverse’ does the opposite. The actual direction therefore depends on ‘direction’ and ‘overflow-style’ of the element, as follows:

‘overflow-style’ | ‘direction’ | ‘forward’ | ‘reverse’
‘marquee-line’ | ‘ltr’ | left | right
 | ‘rtl’ | right | left
‘marquee-block’ |  | up | down

Note that ‘marquee-style: alternate’ moves content in the opposite direction from this table on every other loop.

Note that the ‘direction’ property is often set by rules in the UA style sheet based on mark-up in the document, as recommended in CSS 2.1 [CSS21] section 9.10 (“Text direction: the direction and unicode-bidi properties”).

9. The ‘marquee-speed’ property

Name: | marquee-speed
Value: | slow | normal | fast
Initial: | normal
Applies to: | same as ‘overflow’
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified

This property determines how fast the content scrolls. The actual speed depends on the UA and the type of content. But, for a given UA and a given element, the following must always be true: slow < normal < fast.

10. Conformance

A document or implementation cannot conform to this module alone, but can claim conformance as part of conforming to CSS or another language that normatively references this module. An example of such a language is the CSS Mobile Profile [CSS-MOBILE]. Conformance is defined for the following kinds of objects. UAs may fall in more than one category.

style sheet
A CSS style sheet (or a complete unit of another language that normatively references this module) conforms, if, for all properties from this module that it contains, it satisfies the syntax defined here.
UA that does not render
A UA that reads style sheets without rendering any content (e.g., a validator or pretty-printer), conforms if it accepts all the style sheets that satisfy the syntax defined by this module.
UA that generates CSS
A UA that generates style sheets or CSS fragments in the context of some other language (e.g., an authoring tool or pretty-printer), conforms if, for all properties defined here, it only generates syntax that conforms to this module.
renderer
A UA that renders content (e.g., a browser) conforms if it behaves as described by this module as modified by the language it claims conformance to.

For example, the Mobile Profile [CSS-MOBILE] requires that a rendering UA behave as described here for all properties, while the Print Profile [CSS-PRINT] allows a UA to ignore them.

11. Acknowledgments

The marquee properties were first described in “Wireless CSS,” the CSS profile of the Open Mobile Alliance (OMA), now unified with the CSS Mobile Profile [CSS-MOBILE].

Among the members of the CSS working group, Elika Etemad deserves special thanks, for giving so many concrete suggestions for improvements.

12. Changes

This document is the same as the last draft, except for one non-normative change. The “disposition of comments” explains in more detail how the (two) comments on the last draft were answered.

References

Normative references:

[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 19 July 2007. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2007/CR-CSS21-20070719

Informative references:

[CSS-MOBILE]
Svante Schubert. CSS Mobile Profile 2.0. 19 October 2007. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2007/WD-css-mobile-20071019
[CSS-PRINT]
Melinda Grant. CSS Print Profile. 13 October 2006. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2006/WD-css-print-20061013
[CSS3CASCADE]
Håkon Wium Lie. CSS3 module: Cascading and inheritance. 15 December 2005. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2005/WD-css3-cascade-20051215
[CSS3TEXTLAYOUT]
Elika J. Etemad; Paul Nelson. CSS3 Text Layout Module. (forthcoming). W3C Working Draft. (Work in progress.)
[MEDIAQ]
Håkon Wium Lie; Tantek Çelik; Daniel Glazman. Media Queries. 6 June 2007. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2007/CR-css3-mediaqueries-20070606

Index

  • conformance, #
  • CSS Mobile Profile, #
  • direction, #
  • display, #
  • element, #
  • glossary, #
  • margin-left, #
  • margin-right, #
  • marquee-direction, #
  • marquee-play-count, #
  • marquee-speed, #
  • marquee-style, #
  • overflow, #
  • overflow-style, #
  • style sheet, #
  • UA, #
  • used value, #
  • width, #

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
marquee-direction | forward | reverse | forward | same as ‘overflow’ | yes | N/A | visual
marquee-play-count | <non-negative-integer> | infinite | 1 | same as ‘overflow’ | no | N/A | visual
marquee-speed | slow | normal | fast | normal | same as ‘overflow’ | no | N/A | visual
marquee-style | scroll | slide | alternate | scroll | same as ‘overflow’ | no | N/A | visual
overflow-style | auto | marquee-line | marquee-block | auto | same as ‘overflow’ | yes | N/A | visual


CSS3 Media Queries

Media Queries

W3C Candidate Recommendation 27 July 2010

This Version:
http://www.w3.org/TR/2010/CR-css3-mediaqueries-20100727/
Latest Version:
http://www.w3.org/TR/css3-mediaqueries/
Previous Version:
http://www.w3.org/TR/2009/CR-css3-mediaqueries-20090915/
Editors:
Håkon Wium Lie <howcome @opera.com>
Tantek Çelik <tantek @cs.stanford.edu>
Daniel Glazman <daniel.glazman @disruptive-innovations.com>
Anne van Kesteren <annevk@opera.com>

Copyright © 2010 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

HTML4 and CSS2 currently support media-dependent style sheets tailored for different media types. For example, a document may use sans-serif fonts when displayed on a screen and serif fonts when printed. ‘screen’ and ‘print’ are two media types that have been defined. Media queries extend the functionality of media types by allowing more precise labeling of style sheets.

A media query consists of a media type and zero or more expressions that check for the conditions of particular media features. Among the media features that can be used in media queries are ‘width’, ‘height’, and ‘color’. By using media queries, presentations can be tailored to a specific range of output devices without changing the content itself.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document was produced by the CSS Working Group as a Candidate Recommendation.

A Candidate Recommendation is a document that has been widely reviewed and is ready for implementation. W3C encourages everybody to implement this specification and return comments to the (archived) public mailing list www-style@w3.org (see instructions). When sending e-mail, please put the text “css3-mediaqueries” in the subject, preferably like this: “[css3-mediaqueries] …summary of comment…” The editors maintain a draft with proposed changes.

Publication as a Candidate Recommendation does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

For this specification to exit the CR stage, the following conditions shall be met:

  1. There must be at least two interoperable implementations. For the purposes of this criterion, we define the following terms:

    interoperable

    passing the respective test case(s) in the CSS test suite, or, if the implementation is not a Web browser, an equivalent test. Every relevant test in the test suite should have an equivalent test created if such a user agent (UA) is to be used to claim interoperability. In addition if such a UA is to be used to claim interoperability, then there must one or more additional UAs which can also pass those equivalent tests in the same way for the purpose of interoperability. The equivalent tests must be made publicly available for the purposes of peer review.

    implementation

    a user agent which:

    1. implements the specification.
    2. is available (i.e. publicly downloadable or available through some other public point of sale mechanism). This is the "show me" requirement.
    3. is shipped, or is a "nightly build" (i.e., a development version for the next release), but is not experimental (i.e., a version specifically designed to pass the test suite and not intended for daily usage going forward).

  2. There must be a Test Suite.

  3. A minimum of another four weeks of the CR period must elapse. That is, this specification will not exit CR before 24 August 2010. When the specification exits CR, an implementation report will be published. At this point, no such report exists.

The comments received on the last working draft are still available.

Table of contents

  • 1. Background
  • 2. Media Queries
  • 3. Syntax
    • 3.1. Error Handling
  • 4. Media features
    • 4.1. width
    • 4.2. height
    • 4.3. device-width
    • 4.4. device-height
    • 4.5. orientation
    • 4.6. aspect-ratio
    • 4.7. device-aspect-ratio
    • 4.8. color
    • 4.9. color-index
    • 4.10. monochrome
    • 4.11. resolution
    • 4.12. scan
    • 4.13. grid
  • 5. Values
  • 6. Units
    • 6.1. Resolution
  • Acknowledgments
  • References
    • Normative references
    • Other references

1. Background

(This section is not normative.)

HTML4 [HTML401] and CSS2 [CSS21] currently support media-dependent style sheets tailored for different media types. For example, a document may use different style sheets for screen and print. In HTML4, this can be written as:

<link rel="stylesheet" type="text/css" media="screen" href="sans-serif.css">
<link rel="stylesheet" type="text/css" media="print" href="serif.css">

Inside a CSS style sheet, one can declare that sections apply to certain media types:

@media screen {
  * { font-family: sans-serif }
}

The ‘print’ and ‘screen’ media types are defined in HTML4. The complete list of media types in HTML4 is: ‘aural’, ‘braille’, ‘handheld’, ‘print’, ‘projection’, ‘screen’, ‘tty’, ‘tv’. CSS2 defines the same list, deprecates ‘aural’ and adds ‘embossed’ and ‘speech’. Also, ‘all’ is used to indicate that the style sheet applies to all media types.

Media-specific style sheets are supported by several user agents. The most commonly used feature is to distinguish between ‘screen’ and ‘print’.

There have been requests for ways to describe in more detail what type of output devices a style sheet applies to. Fortunately HTML4 foresaw these requests and defined a forward-compatible syntax for media types. Here is a quote from HTML4, section 6.13:

Future versions of HTML may introduce new values and may allow parameterized values. To facilitate the introduction of these extensions, conforming user agents must be able to parse the media attribute value as follows:

  1. The value is a comma-separated list of entries. For example,
    media="screen, 3d-glasses, print and resolution > 90dpi"

    is mapped to:

    "screen"
"3d-glasses"
"print and resolution > 90dpi"
  2. Each entry is truncated just before the first character that isn't a US ASCII letter [a-zA-Z] (Unicode decimal 65-90, 97-122), digit [0-9] (Unicode hex 30-39), or hyphen (45). In the example, this gives:
    "screen"
"3d-glasses"
"print"

Media queries, as described in this specification, build on the mechanism outlined in HTML4. The syntax of media queries fit into the media type syntax reserved in HTML4. The media attribute of HTML4 also exists in XHTML and generic XML. The same syntax can also be used inside in the ‘@media’ and ‘@import’ rules of CSS.

However, the parsing rules for media queries are incompatible with those of HTML4 so that they are consistent with those of media queries used in CSS.

HTML5 [HTML5] (at the moment of writing still work in progress) references the Media Queries specification directly and thus updates the rules for HTML.

2. Media Queries

A media query consists of a media type and zero or more expressions that check for the conditions of particular media features.

Statements regarding media queries in this section assume the syntax section is followed. Media queries that do not conform to the syntax are discussed in the error handling section. I.e. the syntax takes precedence over requirements in this section.

Here is a simple example written in HTML:

<link rel="stylesheet" media="screen and (color)" href="example.css" />

This example expresses that a certain style sheet (example.css) applies to devices of a certain media type (‘screen’) with certain feature (it must be a color screen).

Here the same media query written in an @import-rule in CSS:

@import url(color.css) screen and (color);

A media query is a logical expression that is either true or false. A media query is true if the media type of the media query matches the media type of the device where the user agent is running (as defined in the "Applies to" line), and all expressions in the media query are true.

A shorthand syntax is offered for media queries that apply to all media types; the keyword ‘all’ can be left out (along with the trailing ‘and’). I.e. if the media type is not explicitly given it is ‘all’.

I.e. these are identical:

@media all and (min-width:500px) { … }
@media (min-width:500px) { … }

As are these:

@media (orientation: portrait) { … }
@media all and (orientation: portrait) { … }

Several media queries can be combined in a media query list. A comma-separated list of media queries. If one or more of the media queries in the comma-separated list are true, the whole list is true, and otherwise false. In the media queries syntax, the comma expresses a logical OR, while the ‘and’ keyword expresses a logical AND.

Here is an example of several media queries in a comma-separated list using the an @media-rule in CSS:

@media screen and (color), projection and (color) { … }

If the media query list is empty (i.e. the declaration is the empty string or consists solely of whitespace) it evaluates to true.

I.e. these are equivalent:

@media all { … }
@media { … }

The logical NOT can be expressed through the ‘not’ keyword. The presence of the keyword ‘not’ at the beginning of the media query negates the result. I.e., if the media query had been true without the ‘not’ keyword it will become false, and vice versa. User agents that only support media types (as described in HTML4) will not recognize the ‘not’ keyword and the associated style sheet is therefore not applied.

<link rel="stylesheet" media="not screen and (color)" href="example.css" />

The keyword ‘only’ can also be used to hide style sheets from older user agents. User agents must process media queries starting with ‘only’ as if the ‘only’ keyword was not present.

<link rel="stylesheet" media="only screen and (color)" href="example.css" />

The media queries syntax can be used with HTML, XHTML, XML [XMLSTYLE] and the @import and @media rules of CSS.

Here is the same example written in HTML, XHTML, XML, @import and @media:

<link rel="stylesheet" media="screen and (color), projection and (color)" rel="stylesheet" href="example.css">
<link rel="stylesheet" media="screen and (color), projection and (color)" rel="stylesheet" href="example.css" />
<?xml-stylesheet media="screen and (color), projection and (color)" rel="stylesheet" href="example.css" ?>
@import url(example.css) screen and (color), projection and (color);
@media screen and (color), projection and (color) { … }

The [XMLSTYLE] specification has not yet been updated to use media queries in the media pseudo-attribute.

If a media feature does not apply to the device where the UA is running, expressions involving the media feature will be false.

The media feature ‘device-aspect-ratio’ only applies to visual devices. On an aural device, expressions involving ‘device-aspect-ratio’ will therefore always be false:

<link rel="stylesheet" media="aural and (device-aspect-ratio: 16/9)" href="example.css" />

Expressions will always be false if the unit of measurement does not apply to the device.

The ‘px’ unit does not apply to ‘speech’ devices so the following media query is always false:

<link rel="stylesheet" media="speech and (min-device-width: 800px)" href="example.css" />

Note that the media queries in this example would have been true if the keyword ‘not’ had been added to the beginning of the media query.

To avoid circular dependencies, it is never necessary to apply the style sheet in order to evaluate expressions. For example, the aspect ratio of a printed document may be influenced by a style sheet, but expressions involving ‘device-aspect-ratio’ will be based on the default aspect ratio of the user agent.

User agents are expected, but not required, to re-evaluate and re-layout the page in response to changes in the user environment, for example if the device is tilted from landscape to portrait mode.

3. Syntax

The media query syntax is described in terms of the CSS2 grammar. As such, rules not defined here are defined in CSS2. The media_query_list production defined below replaces the media_list production from CSS2. [CSS21]

media_query_list
 : S* [media_query [ ',' S* media_query ]* ]?
 ;
media_query
 : [ONLY | NOT]? S* media_type S* [ AND S* expression ]*
 | expression [ AND S* expression ]*
 ;
media_type
 : IDENT
 ;
expression
 : '(' S* media_feature S* [ ':' S* expr ]? ')' S*
 ;
media_feature
 : IDENT
 ;

COMMENT tokens, as defined by CSS2, do not occur in the grammar (to keep it readable), but any number of these tokens may appear anywhere between other tokens. [CSS21]

The following new definitions are introduced:

L  l|\\0{0,4}(4c|6c)(\r\n|[ \t\r\n\f])?|\\l
Y  y|\\0{0,4}(59|79)(\r\n|[ \t\r\n\f])?|\\y

The following new tokens are introduced:

{O}{N}{L}{Y}      {return ONLY;}
{N}{O}{T}         {return NOT;}
{A}{N}{D}         {return AND;}
{num}{D}{P}{I}    {return RESOLUTION;}
{num}{D}{P}{C}{M} {return RESOLUTION;}

RESOLUTION is to be added to the CSS2 term production.

CSS style sheets are generally case-insensitive, and this is also the case for media queries.

In addition to conforming to the syntax, each media query needs to use media types and media features according to their respective specification in order to be considered conforming.

Only the first media query is conforming in the example below because the "example" media type does not exist.

@media all { body { background:lime } }
@media example { body { background:red } }

3.1. Error Handling

For media queries that are not conforming user agents need to follow the rules described in this section.

  • Unknown media types. Unknown media types evaluate to false. Effectively, they are treated identically to known media types that do not match the media type of the device.

    The media query "unknown" will evaluate to false, unless unknown is actually a supported media type. Similarly, "not unknown" will evaluate to true.

    Unknown media types are distinct from media types that do not actually match the IDENT production. Those fall under the malformed media query clause.

  • Unknown media features. User agents are to represent a media query as "not all" when one of the specified media features is not known.

    <link rel="stylesheet" media="screen and (max-weight: 3kg) and (color), (color)" href="example.css" />

    In this example, the first media query will be represented as "not all" and evaluate to false and the second media query is evaluated as if the first had not been specified, effectively.

    @media (min-orientation:portrait) { … }

    Is represented as "not all" because the ‘orientation’ feature does not accept the ‘min-’ prefix.

  • Unknown media feature values. As with unknown media features, user agents are to represent a media query as "not all" when one of the specified media feature values is not known.

    The media query (color:20example) specifies an unknown value for the ‘color’ media feature and is therefore represented as "not all".

    This media query is represented as "not all" because negative lengths are not allowed for the ‘width’ media feature:

    @media (min-width: -100px) { … }

  • Malformed media query. User agents are to handle unexpected tokens encountered while parsing a media query by reading until the end of the media query, while observing the rules for matching pairs of (), [], {}, "", and '', and correctly handling escapes. Media queries with unexpected tokens are represented as "not all". [CSS21]

    @media (example, all,), speech { /* only applicable to speech devices */ }
@media &test, screen           { /* only applicable to screen devices */ }

    The following is an malformed media query because having no space between ‘and’ and the expression is not allowed. (That is reserved for the functional notation syntax.)

    @media all and(color) { … }

    Media queries are expected to follow the error handling rules of the host language as well.

    @media test;,all { body { background:lime } }

    … will not apply because the semicolon terminates the @media rule in CSS.

4. Media features

Syntactically, media features resemble CSS properties: they have names and accept certain values. There are, however, several important differences between properties and media features:

  • Properties are used in declarations to give information about how to present a document. Media features are used in expressions to describe requirements of the output device.
  • Most media features accept optional ‘min-’ or ‘max-’ prefixes to express "greater or equal to" and "smaller or equal to" constraints. This syntax is used to avoid "<" and ">" characters which may conflict with HTML and XML. Those media features that accept prefixes will most often be used with prefixes, but can also be used alone.
  • Properties always require a value to form a declaration. Media features, on the other hand, can also be used without a value. For a media feature feature, (feature) will evaluate to true if (feature:x) will evaluate to true for a value x other than zero or zero followed by a unit identifier (i.e., other than 0, 0px, 0em, etc.). Media features that are prefixed by min/max cannot be used without a value. When a media feature prefixed with min/max is used without a value it makes the media query malformed.
  • Properties may accept more complex values, e.g., calculations that involve several other values. Media features only accept single values: one keyword, one number, or a number with a unit identifier. (The only exceptions are the ‘aspect-ratio’ and ‘device-aspect-ratio’ media features.)

For example, the ‘color’ media feature can form expressions without a value (‘(color)’), or with a value (‘(min-color: 1)’).

This specification defines media features usable with visual and tactile devices. Similarly, media features can be defined for aural media types.

4.1. width

Value: <length>
Applies to: visual and tactile media types
Accepts min/max prefixes: yes

The ‘width’ media feature describes the width of the targeted display area of the output device. For continuous media, this is the width of the viewport (as described by CSS2, section 9.1.1 [CSS21]) including the size of a rendered scroll bar (if any). For paged media, this is the width of the page box (as described by CSS2, section 13.2 [CSS21]).

A specified <length> cannot be negative.

For example, this media query expresses that the style sheet is usable on printed output wider than 25cm:

<link rel="stylesheet" media="print and (min-width: 25cm)" href="http://…" />

This media query expresses that the style sheet is usable on devices with viewport (the part of the screen/paper where the document is rendered) widths between 400 and 700 pixels:

@media screen and (min-width: 400px) and (max-width: 700px) { … }

This media query expresses that style sheet is usable on screen and handheld devices if the width of the viewport is greater than 20em.

@media handheld and (min-width: 20em),
  screen and (min-width: 20em) { … }

The ‘em’ value is relative to the font size of the root element.

4.2. height

Value: <length>
Applies to: visual and tactile media types
Accepts min/max prefixes: yes
POWERED BY HeroNote

The ‘height’ media feature describes the height of the targeted display area of the output device. For continuous media, this is the height of the viewport including the size of a rendered scroll bar (if any). For paged media, this is the height of the page box.

A specified <length> cannot be negative.

4.3. device-width

Value: <length>
Applies to: visual and tactile media types
Accepts min/max prefixes: yes

The ‘device-width’ media feature describes the width of the rendering surface of the output device. For continuous media, this is the width of the screen. For paged media, this is the width of the page sheet size.

A specified <length> cannot be negative.

@media screen and (device-width: 800px) { … }

In the example above, the style sheet will apply only to screens that currently displays exactly 800 horizontal pixels. The ‘px’ unit is of the logical kind, as described in the Units section.

4.4. device-height

Value: <length>
Applies to: visual and tactile media types
Accepts min/max prefixes: yes

The ‘device-height’ media feature describes the height of the rendering surface of the output device. For continuous media, this is the height of the screen. For paged media, this is the height of the page sheet size.

A specified <length> cannot be negative.

<link rel="stylesheet" media="screen and (device-height: 600px)" />

In the example above, the style sheet will apply only to screens that have exactly 600 vertical pixels. Note that the definition of the ‘px’ unit is the same as in other parts of CSS.

4.5. orientation

Value: portrait | landscape
Applies to: bitmap media types
Accepts min/max prefixes: no

The ‘orientation’ media feature is ‘portrait’ when the value of the ‘height’ media feature is greater than or equal to the value of the ‘width’ media feature. Otherwise ‘orientation’ is ‘landscape’.

@media all and (orientation:portrait) { … }
@media all and (orientation:landscape) { … }

4.6. aspect-ratio

Value: <ratio>
Applies to: bitmap media types
Accepts min/max prefixes: yes

The ‘aspect-ratio’ media feature is defined as the ratio of the value of the ‘width’ media feature to the value of the ‘height’ media feature.

4.7. device-aspect-ratio

Value: <ratio>
Applies to: bitmap media types
Accepts min/max prefixes: yes

The ‘device-aspect-ratio’ media feature is defined as the ratio of the value of the ‘device-width’ media feature to the value of the ‘device-height’ media feature.

For example, if a screen device with square pixels has 1280 horizontal pixels and 720 vertical pixels (commonly referred to as "16:9"), the following Media Queries will all match the device:

@media screen and (device-aspect-ratio: 16/9) { … }
@media screen and (device-aspect-ratio: 32/18) { … }
@media screen and (device-aspect-ratio: 1280/720) { … }
@media screen and (device-aspect-ratio: 2560/1440) { … }

4.8. color

Value: <integer>
Applies to: visual media types
Accept min/max prefixes: yes

The ‘color’ media feature describes the number of bits per color component of the output device. If the device is not a color device, the value is zero.

A specified <integer> cannot be negative.

For example, these two media queries express that a style sheet applies to all color devices:

@media all and (color) { … }
@media all and (min-color: 1) { … }

This media query expresses that a style sheet applies to color devices with 2 or more bits per color component:

@media all and (min-color: 2) { … }

If different color components are represented by different number of bits, the smallest number is used.

For instance, if an 8-bit color system represents the red component with 3 bits, the green component with 3 bits and the blue component with 2 bits, the ‘color’ media feature will have a value of 2.

In a device with indexed colors, the minimum number of bits per color component in the lookup table is used.

The described functionality is only able to describe color capabilities at a superficial level. If further functionality is required, RFC2531 [RFC2531] provides more specific media features which may be supported at a later stage.

4.9. color-index

Value: <integer>
Applies to: visual media types
Accepts min/max prefixes: yes

The ‘color-index’ media feature describes the number of entries in the color lookup table of the output device. If the device does not use a color lookup table, the value is zero.

A specified <integer> cannot be negative.

For example, here are two ways to express that a style sheet applies to all color index devices:

@media all and (color-index) { … }
@media all and (min-color-index: 1) { … }

This media query expresses that a style sheet applies to a color index device with 256 or more entries:

<?xml-stylesheet media="all and (min-color-index: 256)"
  href="http://www.example.com/…" ?>

4.10. monochrome

Value: <integer>
Applies to: visual media types
Accepts min/max prefixes: yes

The ‘monochrome’ media feature describes the number of bits per pixel in a monochrome frame buffer. If the device is not a monochrome device, the output device value will be 0.

A specified <integer> cannot be negative.

For example, here are two ways to express that a style sheet applies to all monochrome devices:

@media all and (monochrome) { … }
@media all and (min-monochrome: 1) { … }

Express that a style sheet applies to monochrome devices with more than 2 bits per pixels:

@media all and (min-monochrome: 2) { … }

Express that there is one style sheet for color pages and another for monochrome:

<link rel="stylesheet" media="print and (color)" href="http://…" />
<link rel="stylesheet" media="print and (monochrome)" href="http://…" />

4.11. resolution

Value: <resolution>
Applies to: bitmap media types
Accepts min/max prefixes: yes

The ‘resolution’ media feature describes the resolution of the output device, i.e. the density of the pixels. When querying devices with non-square pixels, in ‘min-resolution’ queries the least-dense dimension must be compared to the specified value and in ‘max-resolution’ queries the most-dense dimensions must be compared instead. A ‘resolution’ (without a "min-" or "max-" prefix) query never matches a device with non-square pixels.

For example, this media query expresses that a style sheet is usable on devices with resolution greater than 300 dots per inch:

@media print and (min-resolution: 300dpi) { … }

This media query expresses that a style sheet is usable on devices with resolution greater than 118 dots per centimeter:

@media print and (min-resolution: 118dpcm) { … }

4.12. scan

Value: progressive | interlace
Applies to: "tv" media types
Accepts min/max prefixes: no

The ‘scan’ media feature describes the scanning process of "tv" output devices.

For example, this media query expresses that a style sheet is usable on tv devices with progressive scanning:

@media tv and (scan: progressive) { … }

4.13. grid

Value: <integer>
Applies to: visual and tactile media types
Accepts min/max prefixes: no

The ‘grid’ media feature is used to query whether the output device is grid or bitmap. If the output device is grid-based (e.g., a "tty" terminal, or a phone display with only one fixed font), the value will be 1. Otherwise, the value will be 0.

Only 0 and 1 are valid values. (This includes -0.) Thus everything else creates a malformed media query.

Here are two examples:

@media handheld and (grid) and (max-width: 15em) { … }
@media handheld and (grid) and (device-max-height: 7em) { … }

5. Values

This specification also introduces two new values.

The <ratio> value is a positive (not zero or negative) <integer> followed by optional whitespace, followed by a solidus (‘/’), followed by optional whitespace, followed by a positive <integer>.

The <resolution> value is a positive <number> immediately followed by a unit identifier (‘dpi’ or ‘dpcm’).

Whitespace, <integer>, <number> and other values used by this specification are the same as in other parts of CSS, normatively defined by CSS 2.1. [CSS21]

6. Units

The units used in media queries are the same as in other parts of CSS. For example, the pixel unit represents CSS pixels and not physical pixels.

Relative units in media queries are based on the initial value. For example, in HTML, the ‘em’ unit is relative to the initial value of ‘font-size’.

6.1. Resolution

The ‘dpi’ and ‘dpcm’ units describe the resolution of an output device, i.e., the density of device pixels. Resolution unit identifiers are:

dpi
dots per inch
dpcm
dots per centimeter

In this specification, these units are only used in the ‘resolution’ media feature.

Acknowledgments

This specification is the product of the W3C Working Group on Cascading Style Sheets.

Comments from Björn Höhrmann, Christoph Päper, Chris Lilley, Simon Pieters, Rijk van Geijtenbeek, Sigurd Lerstad, Arve Bersvendsen, Susan Lesch, Philipp Hoschka, Roger Gimson, Steven Pemberton, Simon Kissane, Melinda Grant, and L. David Baron improved this specification.

References

Normative references

[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 8 September 2009. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2009/CR-CSS2-20090908

Other references

[HTML401]
David Raggett; Ian Jacobs; Arnaud Le Hors. HTML 4.01 Specification. 24 December 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-html401-19991224
[HTML5]
Ian Hickson. HTML 5. 24 June 2010. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2010/WD-html5-20100624/
[RFC2531]
G. Klyne; L. McIntyre. Content Feature Schema for Internet Fax. March 1999. Internet RFC 2531. URL: http://www.ietf.org/rfc/rfc2531.txt
[XMLSTYLE]
James Clark. Associating Style Sheets with XML documents. 29 June 1999. W3C Recommendation. URL: http://www.w3.org/1999/06/REC-xml-stylesheet-19990629


CSS3 module- Cascading and inheritance

CSS3 module: Cascading and inheritance

W3C Working Draft 15 December 2005

This version:
http://www.w3.org/TR/2005/WD-css3-cascade-20051215
Latest version:
http://www.w3.org/TR/css3-cascade
Previous version:
http://www.w3.org/TR/2002/WD-css3-cascade-20020219
Editor:
Håkon Wium Lie, Opera Software, howcome@opera.com

Copyright ?2005 W3C ?/SUP> (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

This CSS3 module describes how values are assigned to properties. CSS allows several style sheets to influence the rendering of a document, and the process of combining these style sheets is called "cascading". If no value can be found through cascading, a value can be inherited from the parent element or the property's initial value is used.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text "css3-cascade" in the subject, preferably like this: "[css3-cascade] .summary of comment."

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced under the 24 January 2002 CPP as amended by the W3C Patent Policy Transition Procedure. The Working Group maintains a public list of patent disclosures relevant to this document; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) with respect to this specification should disclose the information in accordance with section 6 of the W3C Patent Policy.

This is a draft of a module of CSS level 3. It will probably be bundled with some other modules before it becomes a W3C Recommendation.

The main purpose of this module is to rewrite the relevant parts of CSS2 as a module for CSS3. With the exception of the 'initial' value and the optional title for '@import' and '@media', all features described in this module also exist in CSS2. Compared to CSS2, the cascading order has been changed in two cases as noted in the text.

Table of contents

  • 1. Dependencies on other modules
  • 2. Introduction
  • 3. Input and output of this module
  • 4. Style sheets including other style sheets: the @import rule
  • 5. Rules for specific media: the @media rule
  • 6. Cascading
  • 7. Inheritance
  • 8. Initial value
  • 9. Computing weight
  • 10. Conformance
  • Acknowledgments
  • References
    • Normative references
    • Other references

1. Dependencies on other modules

This CSS3 module depends on the following other CSS3 modules:

  • Selectors [SELECT], which describes specificity
  • Syntax [CSS3SYN], which describes how to parse CSS style sheets into declarations
  • Media Queries [MEDIAQ], which describe how to restrict style sheets to certain types of devices.

It has non-normative (informative) references to the following other CSS3 modules:

  • Values and Units [CSS3VAL], which describes the computation from specified through computed to actual values

2. Introduction

One of the fundamental design principles of CSS is to allow several style sheets, possibly from different sources, to influence the rendering of a document. This CSS3 module describes how to select one among several conflicting declarations on a given element/property combination. The mechanism used in the selection process is called "cascading". When no declaration attempts to set the value of an element/property combination the value will either be inherited from the parent element, or set to the property's "initial value".

3. Input and output of this module

The input to the cascading and inheritance process is:

  • The set of declarations that apply to the element/property combination in question. It is assumed that declarations that do not apply (e.g. due to the media type, or user selection of style sheets) is not included in the set.
  • The inherited value of the property.
  • The initial value of the property.

The output of the cascading and inheritance process is a single value, known as the specified value.

The specified value is found by using the following pseudo-algorithm:

  1. If the cascading process (described below) yields a winning declaration and the value of the winning declaration is not 'initial' or 'inherit', the value of the winning declaration becomes the specified value.
  2. otherwise, if the value of the winning declaration is 'inherit', the inherited value (see below) becomes the specified value
  3. otherwise, if the value of the winning declaration is 'initial', the initial value (see below) becomes the specified value
  4. otherwise, if the property is inherited, the inherited value becomes the specified value
  5. otherwise, the initial value becomes the specified value

The specified value may need some computation before it can be used. For example, the specified value of the 'font-size' property for a given element may be '10em' which needs to be converted into device-specific units before being used to render a document. Computations on specified values are described in the Values and Units [CSS3VAL] module.

4. Style sheets including other style sheets: the @import rule

[When this section is rewritten to define user agent conformance more clearly, it should state that (1) the media list specified in an @import rule prevents the import from being processed if the medium doesn't match, but it doesn't "associate" the media with the style sheet so that it can't be imported some other way. (2) @import without a medium must ignore any medium specified for the same style sheet in a link from a document.]

The '@import' rule allows users to import style rules from other style sheets. Any '@import' rules must follow all '@charset' rules and precede all other at-rules and rule sets in a style sheet. The '@import' keyword must be followed by the URI of the style sheet to include. A string is also allowed; it will be interpreted as if it had url(.) around it.

The following lines are equivalent in meaning and illustrate both '@import' syntaxes (one with 'url()' and one with a bare string):

@import "mystyle.css";
@import url("mystyle.css");

So that user agents can avoid retrieving resources for unsupported media types, authors may specify media-dependent @import rules. These conditional imports specify comma-separated "media queries" after the URI.

The following rules illustrate how '@import' rules can be made media-dependent:

@import url("fineprint.css") print;
@import url("bluish.css") projection, tv;
@import url("narrow.css") handheld and (max-width: 400px);

The full syntax of the expressions after the URL is defined by the Media Queries specification [MEDIAQ].

In the absence of any media queries, the import is unconditional. Specifying 'all' for the medium has the same effect.

At the end of the '@import' rule (after any media queries), there may be a string that assigns a name to the import.

@import url(layout1.css) screen "Plain style";
@import url(colors1.css) screen "Plain style";
@import url(style4.css) "Four-columns and dark";

Imports with different names (together with any named @media rules, see below) represent alternative style sheets. The UA should provide a way for the user to select an alternative by name.

The rules for which style sheet to import are as follows:

  • If the user has not chosen a style by name (e.g., he has indicated to the UA that he wants the default style), then all '@import's without a name are imported, as well as the first '@import' that has a name and all other '@import's that have the same name.

    If the UA is using the default style, only "Yellow Fish" and the nameless '@import's (shown in bold) are used, the others are skipped:

    @import "common1.css";
@import "yellowfish.css" "Yellow Fish";
@import "simple.css"     "Simple";
@import "extra.css"      "Yellow Fish";
@import "deco-a.css"     "Budapest";
@import "deco-b.css"     "Budapest";
@import "common2.css";

  • If the user has chosen a style be name, then all '@import's without a name are imported, as well as all '@import's with the name chosen by the user.

    If the user has chosen the "Simple" style, only "Simple" and the nameless '@import's (all shown in bold) are used, the others are skipped:

    @import "common1.css";
@import "yellowfish.css" "Yellow Fish";
@import "simple.css"     "Simple";
@import "extra.css"      "Yellow Fish";
@import "deco-a.css"     "Budapest";
@import "deco-b.css"     "Budapest";
@import "common2.css";

Style sheets are only imported if the media query on the '@import' (if any) matches the media for which the UA renders the document.

If an '@import' is skipped, then all '@import's inside the style sheet it points to are also skipped, no matter what their names.

HTML [HTML401] uses the term preferred style sheet for the named style sheets that the author marked as the default. In CSS, these are all style sheets whose name is the first name to occur on any '@import' or '@media'. Alternate style sheets are all other named style sheets. Finally, HTML calls style sheets without a name persistent style sheets, because they are imported together with the preferred ones as well as with any alternatives.

The UA should not only provide the user with a choice of alternative style sheets, but should also allow the user to turn all style sheets off. See [where?]

The list of alternative style sheets that the user can choose from consists of

  • any names in the document source itself (such as title attributes on link and style elements in HTML andtitle pseudo-attributes on <?xml-stylesheet?> instructions),
  • the names of '@media' and '@import' rules that occur in linked style sheets that don't have a name on the link, and
  • the names of '@media' and '@import' rules that occur in style sheets linked from '@import' rules that have no name, recursively.
POWERED BY HeroNote

I.e., the UA must not look for additional names by following links with a title attribute or named '@import' rules.

Are names matched case-sensitively or case-insensitively? Property names and font names are case-insensitive, so it is probably most consistent to treat style sheet names the same way.

Would it be easier to read if we precede the name with a keyword or some punctuation? E.g., '@import url(foo.css) as "Boxed"'.

5. Rules for specific media: the @media rule

An @media rule specifies the target media types (separated by commas) of a set of rules (delimited by curly braces). The '@media' construct allows style sheet rules for various media in the same style sheet:

@media print {
  body { font-size: 12pt; }
  h1 { font-size: 24pt; }
}
@media screen and (color) {
  body { font-size: medium; }
  h1 { font-size: 2em; }
}
@media screen, print {
  body { line-height: 1.2; }
}

The full syntax of the expressions after '@media' is defined by the Media Queries specification [MEDIAQ].

After the media queries, before the "{", there may be a string that assigns a name to the '@media' rule.

@media all "Ultra blue" {
  body { background: blue }
  h1 { color: cyan }
}
@media screen, print "Simple and light" {
  body { background: white; color: #333 }
  h2 { font-size: bigger }
}

All '@media' rules with a name, together with any '@import' rules with the same name, present alternative style sheets. The UA must read the rules inside some '@media' rules and skip others, as follows:

  • If the user has not chosen a style by name, the UA must read all '@media' rules of which (1) the media query matches the UA and (2) that either have no name or whose name is equal to that of the first named '@import' or the first named '@media', whichever comes first.

    If the user wants the UA to use the default style, the following example results in the UA reading the "Reverse video" style, the unnamed '@media' rule and all rules that are not in any '@media' (all shown in bold). We assume the UA uses the 'screen' media.

    body { background: white }
p { text-indent: 2em }

@media screen {
  h1 { font-size: xx-large }
}
@media screen "Reverse video" {
  body { background: black; color: white }
}
@media screen, print "Rainbow style" {
  p { color: #E0D }
}

  • If the user has chosen a style by name, the UA must read all '@media' rules (1) of which the media query matches the UA and (2) that either have no name or whose name is equal to the user's chosen name.

    If the user wants the UA to use the "Rainbow style" style, the following example results in the UA reading the "Rainbow style" '@media' rule, the unnamed '@media' rule and all rules that are not in any '@media' (all shown in bold). We assume the UA uses the 'screen' media.

    @import url(base.css);
@import url(altbase.css) "Reverse video";

body { background: white }

@media screen {
  h1 { font-size: xx-large }
}
@media screen "Reverse video" {
  body { background: black; color: white }
}
@media screen, print "Rainbow style" {
  p { color: #E0D }
}

6. Cascading

The purpose of cascading is to find one winning declaration among the set of declarations that apply for a given element/property combination.

User agents must sort declarations according to the following criteria, in order of importance:

  1. Weight. In CSS3, the weight of a declaration is based on the origin of the declaration and its marked level of importance. See a separate section below for how to compute the weight. The declaration with the highest weight wins.
  2. Specificity. The Selectors module [SELECT] describes how to compute the specificity. The declaration with the highest specificity wins.
  3. Order of appearance. The last declaration wins. Rules in imported style sheets are considered to be before any rules in the style sheet itself. Rules in two imported style sheets are considered to be in the same order as the @import rules themselves.

The sorting process continues until one winning declaration is found.

7. Inheritance

Inheritance is a way of propagating property values from parent elements to their children. Inheritance means that the specified value of a given element/property combination is copied from the computed value of the parent element. The root element, which has no parent element, inherits the initial value of the property.

Some properties are said to be inherited. This means that, unless a value is specified for the element/property combination, the value will be determined by inheritance.

All properties accept the 'inherit' value which explicitly specifies that the value will be determined by inheritance. The 'inherit' value can be used to strengthen inherited values, and it can also be used on properties that are not normally inherited. If the 'inherit' value is set on the root element, the property is assigned its initial value.

8. Initial value

Each property has an initial value which becomes the specified value when cascading and inheritance does not yield a value. Also, the initial value can be explicitly specified with the 'initial' keyword which all properties accept.

9. Computing weight

In order to sort declarations in the cascading process, the weight of a declaration must be known. In CSS3, the weight of a declaration is based on the origin of the declaration and its marked level of importance.

CSS style sheets may have three different origins: author, user, and user agent (UA).

  • Author: The author specifies style sheets for a source document according to the conventions of the document language. For instance, in HTML, style sheets may be included in the document or linked externally.
  • User: The user may be able to specify style information for a particular document. For example, the user may specify a file that contains a style sheet or the user agent may provide an interface that generates a user style sheet (or behave as if it did).
  • User agent: Conforming user agents [add ref] must apply a "default style sheet" (or behave as if they did) prior to all other style sheets for a document. A user agent's default style sheet should present the elements of the document language in ways that satisfy general presentation expectations for the document language (e.g., for visual browsers, the EM element in HTML is presented using an italic font). See "Appendix D. Default style sheet for HTML 4" [CSS21] for a recommended default style sheet for HTML 4.0 documents.

Each CSS declaration can have two levels of importance: normal (which is default) and important (which must be marked). The CSS3 syntax module [CSS3SYN] describes how declarations are marked as important.

The weight of style sheets from the various origins, in ascending order, is:

  1. User agent style sheets
  2. User normal style sheets
  3. Author normal style sheets
  4. Author important style sheets
  5. User important style sheets

By default, this strategy gives author declarations more weight than those of the user. It is therefore important that the UA give the user the ability to turn off the influence of a certain style sheet, e.g., through a pull-down menu.

Declarations in imported style sheets have lower weight than declarations in the style sheet from where they are imported. Imported style sheets can themselves import and override other style sheets, recursively, and the same precedence declarations apply.

If the user agent chooses to honor presentational hints from other sources than style sheets, these hints must be given the same weight as the user agent's default style sheet. This rule is intended for presentational hints in HTML.

Note that non-CSS presentational hints had a higher weight in CSS2.

10. Conformance

[TBD]

Acknowledgments

[acknowledgments]

References

Normative references

[CSS3SYN]
L. David Baron. CSS3 module: Syntax. 13 August 2003. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2003/WD-css3-syntax-20030813
[CSS3VAL]
Håkon Wium Lie; Chris Lilley. CSS3 module: Values and Units. 13 July 2001. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2001/WD-css3-values-20010713
[MEDIAQ]
Håkon Wium Lie; Tantek Çelik; Daniel Glazman. Media Queries. 8 July 2002. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2002/CR-css3-mediaqueries-20020708
[SELECT]
Daniel Glazman; et al. Selectors. 13 November 2001. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2001/CR-css3-selectors-20011113

Other references

[CSS21]
Bert Bos; et al. Cascading Style Sheets, level 2 revision 1. 25 February 2004. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2004/CR-CSS21-20040225
[HTML401]
David Raggett; Arnaud Le Hors; Ian Jacobs. HTML 4.01 Specification. 24 December 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-html401-19991224


CSS3 module- Color

CSS3 module: Color

W3C Working Draft, 5 March 2001

This version:
http://www.w3.org/TR/2001/WD-css3-color-20010305
Latest version:
http://www.w3.org/TR/css3-color
Previous version:
http://www.w3.org/1999/06/WD-css3-iccprof-19990623
Editor:
Tantek Çelik (Microsoft Corporation) <tantekc@microsoft.com>
Contributors:
Chris Lilley (W3C) <chris@w3.org>
Brad Pettit (Microsoft Corporation) <bradp@microsoft.com>

Copyright © 2001 W3C ® (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.

Abstract

CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and XML documents on screen, on paper, in speech, etc. To color elements in a document, it uses color related properties and respective values. This draft describes the properties and values that are proposed for CSS level 3. It includes and extends them from properties and values of CSS level 2.

Status of this document

This document is a draft of one of the "modules" for the upcoming CSS3 specification. It not only describes the color related properties and values that already exist in CSS1 and CSS2, but also proposes new properties and values for CSS3 as well. The Working Group doesn't expect that all implementations of CSS3 will implement all properties or values. Instead, there will probably be a small number of variants of CSS3, so-called "profiles". For example, it may be that only the profile for 32-bit color user agents will include all of the proposed color related properties and values.

The current draft is the successor to "Color Profiles for CSS3" (22 June 1999) and is the result of merging with the relevant parts of the following Recommendations and Working Drafts:

  • HTML40
  • CSS2
  • "User Interface for CSS3" (16 February 2000)
  • "Scalable Vector Graphics (SVG) 1.0" (3 March 2000)

This document is a working draft of the CSS & FP working group which is part of the style activity.

Comments on, and discussions of this draft can be sent to the (archived) public mailing list www-style@w3.org (see instructions). W3C Members can also send comments directly to the CSS & FP working group.

It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress." A list of current W3C Recommendations and other technical documents can be found at http://www.w3.org/TR/.

Table of contents

  • 1. Introduction
  • 2. Dependencies
  • 3. Color properties
    • 3.1. Foreground color: the 'color' property
      • 3.1.1. Gamma correction
    • 3.2. Transparency: the 'opacity' property
    • 3.3. ICC Color Profile: the 'color-profile' property
    • 3.4. The 'rendering-intent' property
  • 4. Color units
    • 4.1. [HTML4] color keywords
    • 4.2. Numerical RGB color values
    • 4.3. X11 color keywords
    • 4.4. CSS System Colors
      • 4.4.1. CSS2 User preferences for colors
      • 4.4.2. 'flavor' system color
    • 4.5. Notes on using colors
  • 5. Sample style sheet for HTML 4.0
  • Acknowledgments
  • References
    • Normative
    • Informative
  • Index

1. Introduction

CSS3 is a set of modules, divided up and profiled in order to simplify the specification, and to allow implementors the flexibility of supporting the particular modules appropriate for their implementations.

This module describes CSS properties which allow authors to specify the foreground color and opacity of an element. Additional properties allow specification of the ICC color profile and rendering intent of image content.

2. Dependencies

This CSS3 module depends on the following other CSS3 modules:

  • CSS3 Syntax / Grammar
  • CSS3 Values, Units

The following CSS3 modules depend on this CSS3 module:

  • CSS3 Box Model
  • CSS3 Background
  • CSS3 User Interface
  • CSS3 SVG

3. Color properties

3.1. Foreground color: the 'color' property

Name: | color
Value: | <color> | inherit | attr(X,color)
Initial: | depends on user agent
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual

This property describes the foreground color of an element's text content. There are different ways to specify red:

Example(s):

EM { color: red }              /* predefined color name */
EM { color: rgb(255,0,0) }     /* RGB range 0-255   */
<color>
Color units are defined in a following section.
attr(X,color)
This function returns as a color the value of attribute X for the subject of the selector. The attribute value is parsed by the CSS processor as a <color>. If the subject of the selector doesn't have an attribute X, or if the value of attribute X is not a valid <color>, the declaration is ignored. The case-sensitivity of attribute names depends on the document language. Note. In CSS3, it is not possible to refer to attribute values for other elements of the selector.

3.1.1. Gamma correction

For information about gamma issues, please consult the the Gamma Tutorial in the PNG specification ([PNG10]).

In the computation of gamma correction, UAs displaying on a CRT may assume an ideal CRT and ignore any effects on apparent gamma caused by dithering. That means the minimal handling they need to do on current platforms is:

PC using MS-Windows
none
Unix using X11
none
Mac using QuickDraw
apply gamma 1.45 [ICC32] (ColorSync-savvy applications may simply pass the sRGB ICC profile to ColorSync to perform correct color correction)
SGI using X
apply the gamma value from /etc/config/system.glGammaVal (the default value being 1.70; applications running on Irix 6.2 or above may simply pass the sRGB ICC profile to the color management system)
NeXT using NeXTStep
apply gamma 2.22

"Applying gamma" means that each of the three R, G and B must be converted to R'=Rgamma, G'=Ggamma, B'=Bgamma, before being handed to the OS.

This may rapidly be done by building a 256-element lookup table once per browser invocation thus:

for i := 0 to 255 do
  raw := i / 255.0;
  corr := pow (raw, gamma);
  table[i] := trunc (0.5 + corr * 255.0)
end

which then avoids any need to do transcendental math per color attribute, far less per pixel.

3.2. Transparency: the 'opacity' property

Opacity can be thought of conceptually as a postprocessing operation. Conceptually, after the element is rendered into an RGBA offscreen image, the opacity setting specifies how to blend the offscreen rendering into the current composite rendering.

Name: | opacity
Value: | <alphavalue> | inherit
Initial: | 1
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | visual
<alphavalue>
The uniform opacity setting to be applied across an entire element including its outline, border and background if any. Any values outside the range 0.0 (fully transparent) to 1.0 (fully opaque) will be clipped to this range. If the element is a container element, then the effect is as if the contents of the element were blended against the current rendering composite using a mask where the value of each pixel of the mask is <alphavalue>.

3.3. ICC Color Profile: the 'color-profile' property

Name: | color-profile
Value: | auto | sRGB | <uri> | inherit
Initial: | auto
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual

This property permits the specification of a source color profile other than the default.

auto
This is the default behavior. All colors are presumed to be defined in the sRGB color space unless a more precise embedded profile is specified within content data. For images that do have a profile built into their data, that profile is used. For images that do not have a profile, the sRGB profile is used so that the colors in these images can be kept "in synch" with the colors specified in CSS and HTML.
sRGB
The source profile is assumed to be sRGB. This differs from auto in that it overrides an embedded profile inside an image.
<uri>
The name or location of a standard ICC profile resource. Just like specifying sRGB, it overrides an embedded profile. Due to the size of profiles, the <uri> may specify a special name representing a standard profile. The name sRGB, being the standard WWW color space, is defined separately because of its significance, although the rules regarding application of any special profile should be identical.

Example(s):

/* use the specified profile,
   even if the image contains an embedded profile */
IMG { color-profile: "http://www.colors.corp/images/profiles/mah314.icm" }

Note. SVG defines an '@color-profile' rule which permits the author to set both color-profile, and rendering-intent. The editor expects to include the '@color-profile' rule in a future draft of this document.

3.4. The 'rendering-intent' property

POWERED BY HeroNote
Name: | rendering-intent
Value: | auto | perceptual | relative-colorimetric | saturation | absolute-colorimetric | inherit
Initial: | auto
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual

This property permits the specification of a color profile rendering intent other than the default. The behavior of values other than auto and inherit are defined by the International Color Consortium standard.

auto
This is the default behavior. The user-agent determines the best intent based on the content type. For image content containing an embedded profile, it should be assumed that the intent specified within the profile is the desired intent. Otherwise, the user agent should use the current profile (based on the color-profile style) and force the intent, overriding any intent that may be stored in the profile itself.

4. Color units

A <color> is either a keyword or a numerical RGB specification.

4.1. [HTML4] color keywords

The list of HTML4 keyword color names is: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. The color names are case-insensitive.

Color names and sRGB values
· | Black = #000000 | · | Green = #008000
· | Silver = #C0C0C0 | · | Lime = #00FF00
· | Gray = #808080 | · | Olive = #808000
· | White = #FFFFFF | · | Yellow = #FFFF00
· | Maroon = #800000 | · | Navy = #000080
· | Red = #FF0000 | · | Blue = #0000FF
· | Purple = #800080 | · | Teal = #008080
· | Fuchsia = #FF00FF | · | Aqua = #00FFFF

Example(s):

BODY {color: black; background: white }
H1 { color: maroon }
H2 { color: olive }

4.2. Numerical RGB color values

The RGB color model is used in numerical color specifications. These examples all specify the same color:

Example(s):

EM { color: #f00 }              /* #rgb */
EM { color: #ff0000 }           /* #rrggbb */
EM { color: rgb(255,0,0) }      /* integer range 0 - 255 */
EM { color: rgb(100%, 0%, 0%) } /* float range 0.0% - 100.0% */

The format of an RGB value in hexadecimal notation is a '#' immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This ensures that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display.

The format of an RGB value in the functional notation is 'rgb(' followed by a comma-separated list of three numerical values (either three integer values or three percentage values) followed by ')'. The integer value 255 corresponds to 100%, and to F or FF in the hexadecimal notation: rgb(255,255,255) = rgb(100%,100%,100%) = #FFF. Whitespace characters are allowed around the numerical values.

All RGB colors are specified in the sRGB color space (see [SRGB]). User agents may vary in the fidelity with which they represent these colors, but using sRGB provides an unambiguous and objectively measurable definition of what the color should be, which can be related to international standards (see [COLORIMETRY]).

Values outside the device gamut should be clipped: the red, green, and blue values must be changed to fall within the range supported by the device. For a typical CRT monitor, whose device gamut is the same as sRGB, the three rules below are equivalent:

Example(s):

EM { color: rgb(255,0,0) }       /* integer range 0 - 255 */
EM { color: rgb(300,0,0) }       /* clipped to rgb(255,0,0) */
EM { color: rgb(255,-10,0) }     /* clipped to rgb(255,0,0) */
EM { color: rgb(110%, 0%, 0%) }  /* clipped to rgb(100%,0%,0%) */

Other devices, such as printers, have different gamuts to sRGB; some colors outside the 0..255 sRGB range will be representable (inside the device gamut), while other colors inside the 0..255 sRGB range will be outside the device gamut and will thus be clipped.

4.3. X11 color keywords

The table below provides a list of the X11 colors supported by popular browsers. The two color swatches on the left illustrate setting the background color of a table cell in two ways: The first column uses the named color value, and the second column uses the numeric color value, which should be the same.

Named | Numeric | Color Name | Hex RGB | Decimal
 |  | AliceBlue | #F0F8FF | 240,248,255
 |  | AntiqueWhite | #FAEBD7 | 250,235,215
 |  | Aqua | #00FFFF | 0,255,255
 |  | Aquamarine | #7FFFD4 | 127,255,212
 |  | Azure | #F0FFFF | 240,255,255
 |  | Beige | #F5F5DC | 245,245,220
 |  | Bisque | #FFE4C4 | 255,228,196
 |  | Black | #000000 | 0,0,0
 |  | BlanchedAlmond | #FFEBCD | 255,235,205
 |  | Blue | #0000FF | 0,0,255
 |  | BlueViolet | #8A2BE2 | 138,43,226
 |  | Brown | #A52A2A | 165,42,42
 |  | BurlyWood | #DEB887 | 222,184,135
 |  | CadetBlue | #5F9EA0 | 95,158,160
 |  | Chartreuse | #7FFF00 | 127,255,0
 |  | Chocolate | #D2691E | 210,105,30
 |  | Coral | #FF7F50 | 255,127,80
 |  | CornflowerBlue | #6495ED | 100,149,237
 |  | Cornsilk | #FFF8DC | 255,248,220
 |  | Crimson | #DC143C | 220,20,60
 |  | Cyan | #00FFFF | 0,255,255
 |  | DarkBlue | #00008B | 0,0,139
 |  | DarkCyan | #008B8B | 0,139,139
 |  | DarkGoldenrod | #B8860B | 184,134,11
 |  | DarkGray | #A9A9A9 | 169,169,169
 |  | DarkGreen | #006400 | 0,100,0
 |  | DarkKhaki | #BDB76B | 189,183,107
 |  | DarkMagenta | #8B008B | 139,0,139
 |  | DarkOliveGreen | #556B2F | 85,107,47
 |  | DarkOrange | #FF8C00 | 255,140,0
 |  | DarkOrchid | #9932CC | 153,50,204
 |  | DarkRed | #8B0000 | 139,0,0
 |  | DarkSalmon | #E9967A | 233,150,122
 |  | DarkSeaGreen | #8FBC8F | 143,188,143
 |  | DarkSlateBlue | #483D8B | 72,61,139
 |  | DarkSlateGray | #2F4F4F | 47,79,79
 |  | DarkTurquoise | #00CED1 | 0,206,209
 |  | DarkViolet | #9400D3 | 148,0,211
 |  | DeepPink | #FF1493 | 255,20,147
 |  | DeepSkyBlue | #00BFFF | 0,191,255
 |  | DimGray | #696969 | 105,105,105
 |  | DodgerBlue | #1E90FF | 30,144,255
 |  | FireBrick | #B22222 | 178,34,34
 |  | FloralWhite | #FFFAF0 | 255,250,240
 |  | ForestGreen | #228B22 | 34,139,34
 |  | Fuchsia | #FF00FF | 255,0,255
 |  | Gainsboro | #DCDCDC | 220,220,220
 |  | GhostWhite | #F8F8FF | 248,248,255
 |  | Gold | #FFD700 | 255,215,0
 |  | Goldenrod | #DAA520 | 218,165,32
 |  | Gray | #808080 | 128,128,128
 |  | Green | #008000 | 0,128,0
 |  | GreenYellow | #ADFF2F | 173,255,47
 |  | Honeydew | #F0FFF0 | 240,255,240
 |  | HotPink | #FF69B4 | 255,105,180
 |  | IndianRed | #CD5C5C | 205,92,92
 |  | Indigo | #4B0082 | 75,0,130
 |  | Ivory | #FFFFF0 | 255,255,240
 |  | Khaki | #F0E68C | 240,230,140
 |  | Lavender | #E6E6FA | 230,230,250
 |  | LavenderBlush | #FFF0F5 | 255,240,245
 |  | LawnGreen | #7CFC00 | 124,252,0
 |  | LemonChiffon | #FFFACD | 255,250,205
 |  | LightBlue | #ADD8E6 | 173,216,230
 |  | LightCoral | #F08080 | 240,128,128
 |  | LightCyan | #E0FFFF | 224,255,255
 |  | LightGoldenrodYellow | #FAFAD2 | 250,250,210
 |  | LightGreen | #90EE90 | 144,238,144
 |  | LightGrey | #D3D3D3 | 211,211,211
 |  | LightPink | #FFB6C1 | 255,182,193
 |  | LightSalmon | #FFA07A | 255,160,122
 |  | LightSeaGreen | #20B2AA | 32,178,170
 |  | LightSkyBlue | #87CEFA | 135,206,250
 |  | LightSlateGray | #778899 | 119,136,153
 |  | LightSteelBlue | #B0C4DE | 176,196,222
 |  | LightYellow | #FFFFE0 | 255,255,224
 |  | Lime | #00FF00 | 0,255,0
 |  | LimeGreen | #32CD32 | 50,205,50
 |  | Linen | #FAF0E6 | 250,240,230
 |  | Magenta | #FF00FF | 255,0,255
 |  | Maroon | #800000 | 128,0,0
 |  | MediumAquamarine | #66CDAA | 102,205,170
 |  | MediumBlue | #0000CD | 0,0,205
 |  | MediumOrchid | #BA55D3 | 186,85,211
 |  | MediumPurple | #9370DB | 147,112,219
 |  | MediumSeaGreen | #3CB371 | 60,179,113
 |  | MediumSlateBlue | #7B68EE | 123,104,238
 |  | MediumSpringGreen | #00FA9A | 0,250,154
 |  | MediumTurquoise | #48D1CC | 72,209,204
 |  | MediumVioletRed | #C71585 | 199,21,133
 |  | MidnightBlue | #191970 | 25,25,112
 |  | MintCream | #F5FFFA | 245,255,250
 |  | MistyRose | #FFE4E1 | 255,228,225
 |  | Moccasin | #FFE4B5 | 255,228,181
 |  | NavajoWhite | #FFDEAD | 255,222,173
 |  | Navy | #000080 | 0,0,128
 |  | OldLace | #FDF5E6 | 253,245,230
 |  | Olive | #808000 | 128,128,0
 |  | OliveDrab | #6B8E23 | 107,142,35
 |  | Orange | #FFA500 | 255,165,0
 |  | OrangeRed | #FF4500 | 255,69,0
 |  | Orchid | #DA70D6 | 218,112,214
 |  | PaleGoldenrod | #EEE8AA | 238,232,170
 |  | PaleGreen | #98FB98 | 152,251,152
 |  | PaleTurquoise | #AFEEEE | 175,238,238
 |  | PaleVioletRed | #DB7093 | 219,112,147
 |  | PapayaWhip | #FFEFD5 | 255,239,213
 |  | PeachPuff | #FFDAB9 | 255,218,185
 |  | Peru | #CD853F | 205,133,63
 |  | Pink | #FFC0CB | 255,192,203
 |  | Plum | #DDA0DD | 221,160,221
 |  | PowderBlue | #B0E0E6 | 176,224,230
 |  | Purple | #800080 | 128,0,128
 |  | Red | #FF0000 | 255,0,0
 |  | RosyBrown | #BC8F8F | 188,143,143
 |  | RoyalBlue | #4169E1 | 65,105,225
 |  | SaddleBrown | #8B4513 | 139,69,19
 |  | Salmon | #FA8072 | 250,128,114
 |  | SandyBrown | #F4A460 | 244,164,96
 |  | SeaGreen | #2E8B57 | 46,139,87
 |  | Seashell | #FFF5EE | 255,245,238
 |  | Sienna | #A0522D | 160,82,45
 |  | Silver | #C0C0C0 | 192,192,192
 |  | SkyBlue | #87CEEB | 135,206,235
 |  | SlateBlue | #6A5ACD | 106,90,205
 |  | SlateGray | #708090 | 112,128,144
 |  | Snow | #FFFAFA | 255,250,250
 |  | SpringGreen | #00FF7F | 0,255,127
 |  | SteelBlue | #4682B4 | 70,130,180
 |  | Tan | #D2B48C | 210,180,140
 |  | Teal | #008080 | 0,128,128
 |  | Thistle | #D8BFD8 | 216,191,216
 |  | Tomato | #FF6347 | 255,99,71
 |  | Turquoise | #40E0D0 | 64,224,208
 |  | Violet | #EE82EE | 238,130,238
 |  | Wheat | #F5DEB3 | 245,222,179
 |  | White | #FFFFFF | 255,255,255
 |  | WhiteSmoke | #F5F5F5 | 245,245,245
 |  | Yellow | #FFFF00 | 255,255,0
 |  | YellowGreen | #9ACD32 | 154,205,50

4.4. CSS System Colors

4.4.1. CSS2 User preferences for colors

In addition to being able to assign pre-defined color values to text, backgrounds, etc., CSS3, like CSS2, allows authors to specify colors in a manner that integrates them into the user's graphic environment. Style rules that take into account user preferences thus offer the following advantages:

  1. They produce pages that fit the user's defined look and feel.
  2. They produce pages that may be more accessible as the current user settings may be related to a disability.

For systems that do not have a corresponding value, the specified value should be mapped to the nearest system attribute, or to a default color.

The following lists additional values for color-related CSS attributes and their general meaning. Any color property can take one of the following names. Although these are case-insensitive, it is recommended that the mixed capitalization shown below be used, to make the names more legible.

ActiveBorder
Active window border.
ActiveCaption
Active window caption.
AppWorkspace
Background color of multiple document interface.
Background
Desktop background.
ButtonFace
Face color for three-dimensional display elements.
ButtonHighlight
Dark shadow for three-dimensional display elements (for edges facing away from the light source).
ButtonShadow
Shadow color for three-dimensional display elements.
ButtonText
Text on push buttons.
CaptionText
Text in caption, size box, and scrollbar arrow box.
GrayText
Grayed (disabled) text. This color is set to #000 if the current display driver does not support a solid gray color.
Highlight
Item(s) selected in a control.
HighlightText
Text of item(s) selected in a control.
InactiveBorder
Inactive window border.
InactiveCaption
Inactive window caption.
InactiveCaptionText
Color of text in an inactive caption.
InfoBackground
Background color for tooltip controls.
InfoText
Text color for tooltip controls.
Menu
Menu background.
MenuText
Text in menus.
Scrollbar
Scroll bar gray area.
ThreeDDarkShadow
Dark shadow for three-dimensional display elements.
ThreeDFace
Face color for three-dimensional display elements.
ThreeDHighlight
Highlight color for three-dimensional display elements.
ThreeDLightShadow
Light color for three-dimensional display elements (for edges facing the light source).
ThreeDShadow
Dark shadow for three-dimensional display elements.
Window
Window background.
WindowFrame
Window frame.
WindowText
Text in windows.

Example(s):

For example, to set the foreground and background colors of a paragraph to the same foreground and background colors of the user's window, write the following:

P { color: WindowText; background-color: Window }

4.4.2. 'flavor' system color

'flavor'
The accent color (typically chosen by the user) to customize the user interface of the user agent itself. User agents may default the 'flavor' color to the dominant accent color used on the physical machine/mechanism that the user is interacting with (frequently a mouse, keyboard, monitor and computer case, often just a laptop), if the it is able to retrieve that information from the platform and machine.

Example(s):

:focus {outline: 1px solid flavor}
  /* puts an outline around the currently focused element that color
coordinates with the browser accent color if any */

Note. The computed value of a System Color keyword value is the keyword itself. In addition, in future CSS specifications, the color property may accept additional System Color values.

4.5. Notes on using colors

Although colors can add significant amounts of information to document and make them more readable, please consider the following guidelines when including color in your documents:

  • Don't use color combinations that cause problems for people with color blindness in its various forms.
  • If you use a background image or set the background color, then be sure to set the various text colors as well.
  • When practical, adopt common conventions to minimize user confusion.

5. Sample style sheet for HTML 4.0

This appendix is informative, not normative.

BODY {
    color: black;
    background: white;
    color-profile: sRGB;
    rendering-intent: auto
}

:link    { color: blue; }
:visited { color: purple; }

IMG,OBJECT {
     color-profile: auto;
     rendering-intent: auto
}

Acknowledgments

Thanks to Brad Pettit for both writing up color-profiles, and for implementing it. Thanks to feedback from Marc Attinasi, David Baron, Bert Bos, Ian Hickson, Steve Zilles. And thanks to Chris Lilley for being the resident CSS Color expert.

References

Normative

[COLORIMETRY]
Colorimetry, Second Edition. CIE Publication 15.2-1986, ISBN 3-900-734-00-3. Available at http://www.hike.te.chiba-u.ac.jp/ikeda/CIE/publ/abst/15-2-86.html.
[CSS2]
Bert Bos, Håkon Wium Lie, Chris Lilley, Ian Jacobs. Cascading Style Sheets, level 2. 12 May 1998. W3C Recommandation. Available at http://www.w3.org/TR/REC-CSS2.
[HTML40]
D. Raggett, A. Le Hors, I. Jacobs. HTML 4.0 Specification. 8 July 1997. W3C Recommendation. Available at http://www.w3.org/TR/REC-html40/.
[ICC32]
ICC Profile Format Specification, version 3.2. 1995. Available at ftp://sgigate.sgi.com/pub/icc/ICC32.pdf.
[PNG10]
T. Boutell ed. PNG (Portable Network Graphics) Specification, Version 1.0. 1 October 1996. Available at http://www.w3.org/TR/REC-png-multi.html.
[SRGB]
M. Anderson, R. Motta, S. Chandrasekar, M. Stokes. "Proposal for a Standard Color Space for the Internet - sRGB". Available at http://www.w3.org/Graphics/Color/sRGB.html.

Informative

[CSSICCPROF]
Brad Pettit, Tantek Çelik, Chris Lilley. Color Profiles for CSS3. 22 June 1999. W3C Working Draft. Available at http://www.w3.org/1999/06/WD-css3-iccprof-19990623.
[HTMLICCPROF]
Apple Computer with input from Microsoft Corporation. Proposal for HTML support of ICC profiles. Available at http://www.apple.com/colorsync/benefits/web/icc-profiles.html.
[SVG]
Jon Ferraiolo. Scalable Vector Graphics (SVG) 1.0 Draft. 03 March 2000. W3C Working Draft. Available at http://www.w3.org/TR/2000/03/WD-SVG-20000303.
[UI]
Tantek Çelik. User Interface for CSS3 Draft. 16 February 2000. W3C Working Draft. Available at http://www.w3.org/TR/2000/WD-css3-userint-20000216.
[X11COLORS]
Robert B. Hess. Colors By Name. 02 November 1996. MSDN Online Web Workshop. Available at http://msdn.microsoft.com/workshop/design/color/x11_names.asp.

Index

  • color
    • names of, #
  • <color>
    • definition of, #


CSS3 module- line

CSS3 module: line

W3C Working Draft 15 May 2002

This version:
http://www.w3.org/TR/2002/WD-css3-linebox-20020515
Latest version:
http://www.w3.org/TR/css3-linebox
Previous version:
none
Editors:
Michel Suignard (Microsoft)
Eric A. Meyer
Authors:
Original CSS2 authors, and
Bert Bos (W3C)
Michel Suignard (Microsoft)
Steve Zilles (Adobe)

Copyright ©2002 W3C ® (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.

Abstract

This document presents a set of CSS line formatting properties. It also includes baseline alignment features as well as related functions like initial line and initial letter effect. It extends on the CSS 2 model [CSS2].

Status of This Document

This document is a working draft of the CSS working group which is part of the Style activity (see summary). It contains a proposal for features to be included in CSS level 3.

Feedback is very much welcome. Comments can be sent directly to the editor, but the mailing list www-style@w3.org (see instructions) is also open and is preferred for discussion of this and other drafts in the Style area.

This working draft may be updated, replaced or rendered obsolete by other W3C documents at any time. It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress". Its publication does not imply endorsement by the W3C membership or the CSS Working Group (members only).

To find the latest version of this working draft, please follow the "Latest version" link above, or visit the list of W3C Technical Reports.

Contents

  • 1. Dependencies on other modules
  • 2. Introduction
  • 3. Line box, Line stacking and Content height
    • 3.1. Inline formatting context
    • 3.2. Line box wrapping
    • 3.3. Inline box progression dimension (height in horizontal flow), the 'text-height' property
    • 3.4. Line height adjustment: the 'line-height' property
    • 3.5. Line Stacking: the 'line-stacking-strategy', 'line-stacking-ruby', 'line-stacking-shift' properties, and the 'line-stacking' shorthand property
  • 4. Baseline alignment
    • 4.1. Baseline information provided by fonts
    • 4.2. Baseline identifiers
    • 4.3. Overview of the baseline alignment process
    • 4.4. Dominant baseline: the 'dominant-baseline' property
    • 4.5. Aligning the alignment point of an element: the 'alignment-baseline' property
    • 4.6. Setting the alignment point: the 'alignment-adjust' property
    • 4.7. Repositioning the dominant baseline: the 'baseline-shift' property
    • 4.8. Vertical alignment: the 'vertical-align' shorthand baseline alignment property
    • 4.9. Inline box alignment: the 'inline-box-align' property
  • 5. Initial line and Drop initial
    • 5.1. Initial line
    • 5.2. Drop Initial overview
    • 5.3. Sizing drop initial, the 'drop-initial-size' and the 'drop-initial-value' properties
    • 5.4. Aligning drop initial: the 'drop-initial-before-align', 'drop-initial-before-adjust', 'drop-initial-after-align' and 'drop-initial-after-adjust' properties
  • 6. Properties index
  • 7. Profiles
  • 8. Glossary
  • Appendix A: Usage of baseline alignment (informative)
  • Acknowledgments
  • References
    • Normative references
    • Other references
  • Changes from Previous Working Draft

1. Dependencies on other modules

This CSS3 module depends on the following other CSS3 modules:

  • Fonts
  • Text
  • Syntax and grammar
  • Values and unit

It has non-normative (informative) references to the following other CSS3 modules:

  • Multi-column layout
  • Ruby

2. Introduction

This modules specifies the presentation aspects of line within block elements and inline elements. It also covers the design of baseline alignment within each line and the placement of drop initial letter (also known as first letter or drop caps). Most of the properties are new to CSS3.

All described properties, in addition to the noted values, take 'initial' and 'inherit'. These values are not repeated in each of the property value enumeration.

This module uses extensively the 'before', 'after', 'start' and 'end' notation to specify the four edges of a box relative to its text advance direction, independently of its absolute positioning in terms of 'top', 'bottom', 'left' and 'right' (corresponding respectively to the 'before', 'after', 'start' and 'end' positions in a typical Western text layout). This notation is also used extensively in [XSL1.0] for the same purpose.

Finally, in this document, requirements are expressed using the key words "MUST", "MUST NOT", "REQUIRED", "SHALL" and "SHALL NOT". Recommendations are expressed using the key words "SHOULD", "SHOULD NOT" and "RECOMMENDED". "MAY" and "OPTIONAL" are used to indicate optional features or behavior. These keywords are used in accordance with [RFC2119]. For legibility these keywords are used in lowercase form.

3. Line box, Line stacking and Content height

This section describes inline boxes formatting, how lines are stacked together and a mechanism to adjust the content height of inline elements.

3.1. Inline formatting context

In an inline formatting context, boxes are laid out in the inline progression direction, one after the other, following the block progression within the containing block. Borders, padding and inline progression margins are respected between these boxes. The boxes may be aligned within the inline progression in different ways: their after-edges or before-edges may be aligned, or the baselines of text within them may be aligned. The rectangular area that contains the boxes that form a line is called a line box.

The inline progression dimension ('width' in horizontal flow) of a line box is determined by its containing block. The block progression dimension ('height' in horizontal flow) of a line box is determined by the rules given in the section on line height calculations. A line box is generally tall (relative) enough for all of the boxes it contains. However, it may be taller than the tallest box it contains (if, for example, boxes are aligned so that baselines line up). When the block progression dimension of a box B is less than the similar dimension of the line box containing it, the alignment of B within the line box is determined by the baseline alignment properties.

When several inline boxes cannot fit within a single line box, they are distributed among two or more block-progression stacked line boxes. Thus, a paragraph is a stack of line boxes.

Line boxes are stacked together following the strategy determined by the 'line-stacking-strategy' property. Depending on the set value, line boxes can be stacked at constant spacing, in a grid manner or with enough space to accommodate all the line boxes. Using a constant spacing may create a 'bleeding' effect between line boxes.

A containing block defines a root inline element which wraps all the inline children of the block element, including the anonymous inline elements. It inherits the inline behaviors that are set for the block element (like 'line-height') and play an important role in some line stacking strategies.

Although margins, borders, and padding of non-replaced elements do not enter into inline box block-progression dimension calculation (and thus the line box calculation), they are still rendered around inline boxes. This means that if the block-progression dimension of a line box is shorter than the outer edges of the boxes it contains, backgrounds and colors of padding and borders may "bleed" into adjacent line boxes. However, in this case, some user agents may use the line box to "clip" the border and padding areas (i.e., not render them).

3.2. Line Box wrapping

In general, the start edge of a line box touches the start edge of its containing block and the end edge touches the end edge of its containing block. However, floating boxes may come between the containing block edge and the line box edge. Thus, although line boxes in the same inline formatting context generally have the same inline progression advance (that of the containing block), they may vary if available inline-progression space is reduced due to floats. Line boxes in the same inline formatting context may vary in block-progression advance or not, depending on the line stacking strategy.

When the total inline-progression advance of the inline boxes on a line is less than the inline-progression dimension of the line box containing them, their inline-progression distribution within the line box is determined by the 'text-align' property. If that property has the value 'justify', the user agent may stretch the inline boxes as well.

Since an inline box may not exceed the inline-progression width of a line box, long inline boxes are split into several boxes and these boxes distributed across several line boxes. When an inline box is split, margins, borders, and padding have no visual effect where the split occurs. Formatting of margins, borders, and padding may not be fully defined if the split occurs within a bidirectional embedding.

Inline boxes may also be split into several boxes within the same line box due to bidirectional text processing.

Here is an example of inline box construction. The following paragraph (created by the HTML block-level element P) contains anonymous text interspersed with the elements EM and STRONG:
<P>Several <EM>emphasized words</EM> appear
<STRONG>in this</STRONG> sentence, dear.</P>

The P element generates a block box that contains five inline boxes, three of which are anonymous:

  • Anonymous: "Several"
  • EM: "emphasized words"
  • Anonymous: "appear"
  • STRONG: "in this"
  • Anonymous: "sentence, dear."

To format the paragraph, the user agent flows the five boxes into line boxes. In this example, the box generated for the P element establishes the containing block for the line boxes. If the containing block is sufficiently wide (relative) , all the inline boxes will fit into a single line box:

 Several emphasized words appear in this sentence, dear.

If not, the inline boxes will be split up and distributed across several line boxes. The previous paragraph might be split as follows:

Several emphasized words appear
in this sentence, dear.

or like this:

Several emphasized
words appear in this
sentence, dear.

In the previous example, the EM box was split into two EM boxes (call them "split1" and "split2"). Margins, borders, padding, or text decorations have no visible effect after split1 or before split2.

Consider the following example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
  <HEAD>
    <TITLE>Example of inline flow on several lines</TITLE>
    <STYLE type="text/css">
      EM {
        padding: 2px;
        margin: 1em;
        border-width: medium;
        border-style: dashed;
        line-height: 2.4em;
      }
    </STYLE>
  </HEAD>
  <BODY>
    <P>Several <EM>emphasized words</EM> appear here.</P>
  </BODY>
</HTML>

Depending on the width of the P, the boxes may be distributed as follows:

Image illustrating the effect of line breaking on the display of margins, borders, and padding. [D]
  • The margin is inserted before "emphasized" and after "words".
  • The padding is inserted before, above, and below "emphasized" and after, above, and below "words". A dashed border is rendered on three sides in each case.

3.3. Inline box progression dimension (height in horizontal flow), the 'text-height' property

Each inline box has a block-progression dimension which is derived from the following parameters: the 'text-height' and 'font-size' properties for non-replaced elements, the height or the width for replaced elements (depending on the text flow being horizontal or vertical respectively) and the stacked block-progression advance for inline-block elements (identical to what is done for block-level elements).

The block-progression dimension determines the position of the padding, border and margin for the element but does not necessarily determines the line stacking progression as this is also controlled by the 'line-stacking-strategy'.

Name: | text-height
Value: | auto | font-size | text-size | max-size
Initial: | auto
Applies to: | inline elements and parents of element with display:ruby-text
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value (except for initial and inherit)

The 'text-height' property determine the block-progression dimension of the text content area of an inline box. Possible values:

auto
The block-progression dimension is based either on the em square determined by the element font-size property value or the cell-height (ascender + descender) related to the element font-size as chosen by the user agent.
font-size
The block-progression dimension is based on the em square as determined by the element font-size.
text-size
The block-progression dimension is based on the cell-height (ascender + descender) related to the element font-size.
max-size
The block-progression dimension is based on the maximum extents toward the before-edge and after-edge of the box obtained by considering all children elements located on the same line, ruby annotations (elements with 'display:ruby-text') and baseline shifted elements.

When more than one font-size is used (this could happen when glyphs are found in different fonts), it is recommended that the largest font-size provides the em square and the cell-height.

Although the 'text-height' property does not apply directly to block elements, it applies to their anonymous children inline elements (if any).

3.4. Line height adjustment: the 'line-height' property

The 'line-height' property allows to control the amount of leading space which is added before and after the block-progression dimension of either an inline box, a line box or both. The 'line-stacking-strategy' property value determines which effects are active. For example, there are line stacking strategies for which leading is not applied to inline boxes, but only to the line boxes. The sum of the possible leading space and the block progression dimension is called the extended block progression dimension. That extended value is not used for border, margin and padding placement but is used for vertical alignment (relative) and line box block progression dimension.

The leading for an inline element is defined as the difference between the block-progression dimension as determined by the 'text-height' property and the computed value of 'line-height'. Half the leading is called the half-leading, each half-leading is located before and after the block-progression dimension of the element. Depending on the value of the 'line-stacking-strategy', the 'line-height' value will specify the exact extended block-progression dimension of each box generated by the element or be ignored. (Except for inline replaced elements, where the block-progression dimension of the box is given by the 'height' or the 'width' property depending on the text flow.) When the line-height value is ignored for an inline element, the extended block progression dimension is identical to the block progression dimension. Anonymous inline elements use the 'text-height' and 'line-height' property values specified for their parent.

Depending on the value of the 'line-stacking-strategy', the 'line-height' value may provide a minimum or exact extended block-progression dimension for each generated inline box and the line boxes. How the leading space is distributed between the before-edge and the after-edge of inline elements within the line box depends on their vertical-align property value.

When applicable, the minimum extended block-progression dimension consists of a minimum ascent above the block's baseline and a minimum descent below it, exactly as if each line box starts with a zero-width (relative) inline box with the blocks' font and line height properties (what TEX calls a 'strut').

Empty inline elements generate empty inline boxes, but these boxes still have a line height, and thus may influence the line box block progression dimension, as if the empty box contained an infinitely narrow letter.

A inline box which otherwise would influence the line box extended progression dimension may be removed from the computation by using a special value of the line-height property: 'none'. This is equivalent to setting its line-height to the font-size of its ancestor block element.

Name: | line-height
Value: | normal | <number> | <length> | <percentage> | none
Initial: | normal
Applies to: | all elements
Inherited: | yes
Percentages: | refer to the font size of the element itself
Media: | visual
Computed value: | see prose

Values for this property have the following meanings:

normal
Tells user agents to set the computed value to a "reasonable" value based on the font size of the element. The value has the same meaning as <number>. We recommend a computed value for 'normal' between 1.0 to 1.2.
<length>
The box height is set to this length. Negative values are illegal. The length is the computed value.
<number>
The computed value of the property is this number multiplied by the element's font size. Negative values are illegal. However, the number, not the computed value, is inherited.
<percentage>
The computed value of the property is this percentage multiplied by the element's computed font size. Negative values are illegal.
none
The computed value of the property is the ancestor block element font-size.

Example(s):

The three rules in the example below have the same resultant line height:

DIV { line-height: 1.2; font-size: 10pt }     /* number */
DIV { line-height: 1.2em; font-size: 10pt }   /* length */
DIV { line-height: 120%; font-size: 10pt }    /* percentage */

When an element contains text that is rendered in more than one font, user agents should determine the 'line-height' value according to the largest font size (when appropriate).

Note that replaced elements have a 'font-size' and a 'line-height' property, even if they are not used directly to determine the extended block progression dimension of the box: 'em' and 'ex' values are relative to values of 'font-size and percentage values for 'vertical-align' are relative to values of the extended block progression dimension.

When the 'line-height' value is less than the font size, the final inline box extended block progression dimension will be less than the font size and the rendered glyphs will "bleed" outside the box. If such a box touches the edge of a line box, the rendered glyphs will also "bleed" into the adjacent line box.

3.5. Line Stacking: the 'line-stacking-strategy', 'line-stacking-ruby', 'line-stacking-shift' properties, and the 'line-stacking' shorthand property

Line stacking is the mechanism by which a line box is determined for each line in a block and then these lines are stacked in the block progression direction resolving any spacing constraints between adjacent lines. The line-stacking strategy covers both the determination of the block progression dimension (height in horizontal flow) of a line box and the rules for spacing line boxes.

All line stacking strategies make use of the properties: 'font-size', 'text-height' and 'line-height'.

The line stacking properties are made of the following properties:

  1. The 'line-stacking-strategy' property determines the overall stacking method,
  2. The 'line-stacking-ruby' property determines how elements with 'display=ruby' are stacked,
  3. The 'line-stacking-shift' property determines how elements which are baseline-shifted are stacked,
  4. Finally the 'line-stacking' property is a short-hand for the previous properties.
Name: | line-stacking-strategy
Value: | inline-line-height | block-line-height | max-height | grid-height
Initial: | inline-line-height
Applies to: | block-level elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value (except for initial and inherit)

This property determines the line stacking strategy for stacked line boxes within a containing block element. The term 'stack-height' is used in the context of this property description to indicate the block-progression advance for the line boxes. Possible values:

inline-line-height
The stack-height is the smallest value that contains the extended block progression dimension of all the inline elements on that line when those elements are properly aligned. Since the line spacing information is already included in the computation of the line box, these line boxes are simply stacked adjacent to one another in the formatted block to which they belong. The 'line-height' property value is taken into account for both the inline elements and the block elements. For inline elements, it defines the extended block progression dimension. For block elements, it defines the minimum extended block progression dimension.
block-line-height
The stack-height is determined by the block element 'line-height' property value. The 'line-height' property value is ignored for inline elements. For alignment purpose, this case is similar to the minimum extended block progression dimension case (strut model). This is the only line-stacking strategy that may cause inline boxes within the line to bleed before and after the line box because the line box is not constrained by its inline boxes.
max-height
The stack-height is the smallest value that contains the block progression dimension of all the inline elements on that line when those elements are properly aligned. The 'line-height' property value is taken into account only for the block elements.
grid-height
The stack-height is the smallest multiple of the block element 'line-height' computed value that can contain the block progression of all the inline elements on that line when those elements are properly aligned. The 'line-height' property value is ignored for inline elements.

When the line-stack strategy dictates that the inline element line-height be ignored, this means that for those elements only their block progression dimensions are considered for the stack-height, not their extended block progression dimensions.

Note. XSL has a similar property with the same name which use different but equivalent values: 'line-height' instead of 'inline-line-height', 'font-height' instead of 'block-line-height'. It also uses 'max-height. The value 'grid-height' is new to the CSS3 property.

Name: | line-stacking-ruby
Value: | exclude-ruby | include-ruby
Initial: | exclude-ruby
Applies to: | block-level elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value (except for initial and inherit)

This property determines the line stacking method for block elements containing ruby annotation elements (element with 'display: ruby-text' or 'display: ruby-text-container'). In all cases the ruby base elements (elements with 'display: ruby-base' or display: ruby-base-container') are considered for line stacking. Possible values:

exclude-ruby
The ruby annotation elements are ignored for line stacking.
include-ruby
The ruby annotation elements are considered for line stacking.

This property is ignored in two cases:

  1. The element text-height property is set to 'max-size'.
  2. The line stacking strategy is set to 'block-line-height'.
Name: | line-stacking-shift
Value: | consider-shifts | disregard-shifts
Initial: | consider-shifts
Applies to: | block-level elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value (except for initial and inherit)

This property determines the line stacking method for block elements containing elements with base-shift. Possible values:

consider-shifts
In determining the stack-height, include the adjusted top-edge and bottom-edge of any characters that have a baseline-shift.
disregard-shifts
In determining the stack-height, include the unshifted top-edge and bottom-edge of any characters that have a baseline-shift.

This property is ignored in two cases:

  1. The element text-height property is set to 'max-size'.
  2. The line stacking strategy is set to 'block-line-height'.

Note. XSL has a similar property with a different name: 'line-height-shift-adjustment' which use the same values.

Finally, the line stacking strategy can be used using the following shorthand:

Name: | line-stacking
Value: | <'line-stacking-strategy'> || <'line-stacking-ruby'> || <'line-stacking-shift'>
Initial: | see individual properties
Applies to: | block-level elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | see individual properties

4. Baseline alignment

Baseline alignment describes the alignment of textual content and based on information contained in font tables associated with font resources. Additional descriptions for these font tables are provided in the CSS3 Fonts module.

4.1. Baseline information provided by fonts

The glyphs of a given script are positioned so that a particular point on each glyph, the alignment-point, is aligned with the alignment-points of the other glyphs in that script. The glyphs of different scripts are typically aligned at different points on the glyph. For example, Western glyphs are aligned on the bottoms of the capital letters, certain Indic glyphs (including glyphs from the Devanagari, Gurmukhi and Bengali scripts) are aligned at the top of a horizontal stroke near the top of the glyphs and East Asian glyphs are aligned either at the bottom or center of the EM box of the glyph. Within a script and within a line of text having a single font-size, the sequence of alignment-points defines, in the inline-progression-direction, a geometric line called a baseline. Western and most other alphabetic and syllabic glyphs are aligned to an "alphabetic" baseline, the above Indic glyphs are aligned to a "hanging" baseline and the East Asian glyphs are aligned to an "ideographic" baseline.

three alignment points

This figure shows the vertical position of the alignment-point for alphabetic and many syllabic scripts, illustrated by a Roman "A"; for certain Indic scripts, illustrated by a Gurmukhi syllable "ji"; and for ideographic scripts, illustrated by the ideographic glyph meaning "country". The thin black rectangle around the ideographic glyph illustrates the EM box for that glyph and shows the typical positioning of the "black marks" of the glyph within the EM box.

A baseline-table specifies the position of one or more baselines in the design space coordinate system. The function of the baseline table is to facilitate the alignment of different scripts with respect to each other when they are mixed on the same text line. Because the desired relative alignments may depend on which script is dominant in a line (or block), there may be a different baseline table for each script. In addition, different alignment positions are needed for horizontal and vertical writing modes. Therefore, the font may have a set of baseline tables: typically, one or more for horizontal writing-modes and zero or more for vertical writing-modes.

different baseline positions

Examples of horizontal and vertical baseline positions. The thin lined box in each example is the "EM box". For the Latin glyphs, only the EM box of the first glyph is shown. Example 1 shows typical Latin text written horizontally. This text is positioned relative to the alphabetic baseline, shown in blue. Example 2 shows a typical ideographic glyph positioned on the horizontal ideographic baseline. Note that the EM Box is positioned differently for these two cases. Examples 3 and 4 show the same set of baselines used in vertical writing. The Latin text, example 3, is shown with a glyph-orientation of 90 degrees which is typical for proportionally space Latin glyphs in vertical writing. Even though the ideographic glyph in Example 4 is positioned on the vertical ideographic baseline, because it is centered in the EM box, all glyphs with the same EM Box are centered, vertically, with respect to one another.

The font tables for a font include font characteristics for the individual glyphs in the font. CSS assumes that the font tables include, for each glyph in the font, one width value, one alignment-baseline and one alignment-point for the horizontal writing-modes. If vertical writing-modes are supported, then each glyph must have another width value, alignment-baseline and alignment-point for the vertical writing-modes. (Even though it is specified as a width, for vertical writing-modes the width is used in the vertical direction.)

The script to which a glyph belongs determines an alignment-baseline to which the glyph is to be aligned. The position of this baseline in the design space coordinate system determines the default block progression direction position of the alignment-point. The inline progression direction position of the alignment-point is on the start-edge of the glyph.

alignment in em box

This figure shows glyphs from three different scripts, each with its EM box and within the EM box, the baseline table applicable to that glyph. The alignment-point of each glyph is shown by an "X" on the start edge of the EM box and by making alignment-baseline blue. The baseline-table of the parent element of the characters that mapped to these glyphs is shown as a set of dashed lines.

4.2. Baseline identifiers

The baseline alignment properties control the alignment of child element with respect to their parent. The positions of these baselines are illustrated in the following figure:

This figure shows samples of Gurmukhi (a hanging Indic script), Latin and ideographic scripts together with most of the baselines defined below. The thin line around the ideographic glyphs symbolizes the EM box in which these glyphs are centered. In this figure, the position of the "text-before-edge" and "text-after-edge" baselines is computed assuming that the "alphabetic" baseline is the dominant-baseline. The "central" baseline has been omitted from the figure, but it lies halfway between the "text-before-edge" and "text-after-edge" baselines, just about where the "math" baseline is shown.

The baseline-identifiers below are used in this specification. Some of these are determined by baseline-tables contained in a font as described in the section describing the baseline information provided by fonts. Others are computed from other font characteristics as described below. Whether determined by the font or computed, a derived baseline-table is constructed with positions of each of the baselines below.

alphabetic

This identifies the baseline used by most alphabetic and syllabic scripts. These include, but are not limited to, many Western, Southern Indic, Southeast Asian (non-ideographic) scripts.

ideographic

This identifies the baseline used by ideographic scripts. For historical reasons, this baseline is at the bottom of the ideographic EM box and not in the center of the ideographic EM box. See the "central" baseline. The ideographic scripts include Chinese, Japanese, Korean, and Vietnamese Chu Nom.

hanging

This identifies the baseline used by certain Indic scripts. These scripts include Devanagari, Gurmukhi and Bengali.

mathematical

This identifies the baseline used by mathematical symbols.

central

This identifies a computed baseline that is at the center of the EM box. This baseline lies halfway between the text-before-edge and text-after-edge baselines.

Note. For ideographic fonts, this baseline is often used to align the glyphs; it is an alternative to the ideographic baseline.

middle

This identifies a baseline that is offset from the alphabetic baseline in the shift-direction by 1/2 the value of the x-height font characteristic. The position of this baseline may be obtained from the font data or, for fonts that have a font characteristic for "x-height", it may be computed using 1/2 the "x-height". Lacking either of these pieces of information, the position of this baseline may be approximated by the "central" baseline.

text-before-edge

This identifies the before-edge of the EM box. The position of this baseline may be specified in the baseline-table or it may be calculated.

Note. The position of this baseline is normally around or at the top of the ascenders, but it may not encompass all accents that can appear above a glyph. For fonts with ascenders, the value of the "ascent" font characteristic is used. For ideographic fonts, the position of this baseline is normally 1 EM in the shift-direction from the "ideographic" baseline. However, some ideographic fonts have a reduced width in the inline-progression-direction to allow tighter setting. When such a font, designed only for vertical writing-modes, is used in a horizontal writing-mode, the "text-before-edge" baseline may be less than 1 EM from the text-after-edge.

text-after-edge

This identifies the after-edge of the EM box. The position of this baseline may be specified in the baseline-table or it may be calculated.

Note. For fonts with descenders, the position of this baseline is normally around or at the bottom of the descenders. For these fonts the value of the "descent" font characteristic is used. For ideographic fonts, the position of this baseline is normally at the "ideographic" baseline.

There are, in addition, two computed baselines that are only defined for line boxes: 'before-edge' and 'after-edge'. For each line box, there is a dominant-baseline, a baseline-table and a baseline-table font-size which are those of the nearest block-level ancestor element and are applied to its root inline element. Depending on the 'line-stacking-strategy' being used, the line stacking progression (also called stack-height) can be different from the line block progression dimension. The 'before-edge' and 'after-edge' baselines are always based on the block progression dimension and are in fact part of its determination.

For an inline element, the extended inline box includes the maximum extent of their static or relative positioned children located in the same line box and may include leading specified by their line-height value. Depending on the line-stacking-strategy value, the extended line box may have a different block progression dimension. For replaced elements the margin extents are always added.

The following text explains the interaction between the line-stacking-strategy and the various baseline alignment parameters.

  • For 'line-stacking-strategy: inline-line-height', all 'line-height' values (set for both inline elements and ancestor block element) participate on the evaluation of the line block progression dimension. The position of the dominant-baseline on the start edge of the line box is determined after all vertical (relative) alignments have been performed on the line. The extended inline boxes of all inline elements include the leading introduced by their line-height value.
  • For 'line-stacking-strategy: block-line-height', the ancestor block 'line-height' value participates on the evaluation of the line block progression dimension. The inline element line-height values are ignored. The position of the dominant-baseline on the start edge of the line box is determined by using a virtual 'zero-width' inline box with the block font and line height properties located on the start edge of the line box. The extended inline boxes of all inline elements do not include any extra leading.
  • For 'line-stacking-strategy: max-height' and 'line-stacking-strategy: grid-height', only the ancestor block 'line-height' value participates on the evaluation of the line block progression dimension. The inline element line-height values are ignored. The position of the dominant-baseline on the start edge of the line box is determined after all vertical (relative) alignments have been performed on the line. The extended inline boxes of all inline elements do not include any extra leading.

The "before-edge" and "after-edge" baselines are defined as follows.

before-edge

The offset of the "before-edge" baseline of the line from the dominant-baseline of the line is determined by ignoring all extended inline boxes whose alignment-baseline is either "before-edge" or "after-edge". For the "before-edge", extents are measured from the dominant-baseline in the direction toward the top (relative) of the extended inline box. The "before-edge" baseline offset is set to the maximum extent of the "before-edges" of the extended inline boxes of the remaining areas. If all the extended inline boxes in a line box are aligned either to the "before-edge" or to the "after-edge", then use the offset of the "text-before-edge" baseline of the line as the offset of the "before-edge" baseline of the line.

after-edge

The offset of the "after-edge" baseline of the line from the dominant-baseline of the line is determined by ignoring all extended inline boxes whose alignment-baseline is after-edge. For the "after-edge", extents are measured from the dominant-baseline in the direction toward the bottom (relative) of the extended inline box. The "after-edge" baseline offset is set to the negative of the maximum of (1) the maximum extent of the "after-edges" of the remaining extended inline boxes and (2) the maximum height of the extended inline boxes that are ignored minus the offset of the "before-edge" baseline of the line.

Note. If all the extended inline boxes in a line box are aligned to the "after-edge" then the specification for the "before-edge" will set the "before-edge" baseline to coincide with the "text-before-baseline" of the line. Then, case (2) above will determine an offset to the "bottom-edge" baseline that will align the "before-edge" of the box with the greatest height to its allocation-rectangle to "before-edge" baseline.

Note. The above specifications for "before-edge" and "after-edge" have the following three properties: (1) all extended inline boxes are below the "before-edge", (2) all extended inline boxes are above the "after-edge", and (3) the distance between the "before-edge" and the "after-edge" cannot be decreased without violating (1) or (2). The specified placement of the "before-edge" and "after-edge" is not the only way that (1)-(3) can be satisfied, but it is the only way they can be satisfied with the smallest possible offset to the "before-edge".

For the purpose of before-edge and after-edge baseline computation, inline boxes include the maximum extent of their static or relative positioned children located in the same line box. Maximum alignment extents are measured by including the half leading extent in the appropriate direction for non replaced elements and by using the margin extents for replaced elements.

Examples showing "before-edge" and "after-edge" alignment:

aligning text and images

The rectangles with lines or arrows are images with an intrinsic size as shown. The rectangles with no arrows represent images that receive the default, dominant baseline, alignment. The alignment of the other rectangles is at the furthest point from the arrow head (which is in the middle when there are two arrowheads). Examples 1 and 2 show the "before-edge" alignment is determined by the tallest non-"before-edge" aligned objects: in example 1 this is the default aligned, arrowhead free rectangular image and in example 2 this is the double headed arrow rectangle. Examples 3 and 4 show defaulting to the "text-before-edge" when all the boxes have either "before-edge" or "after-edge" alignment. In example 3, the images with "before-edge" alignment has a taller member than do the "after-edge" aligned images. In example 4, the tallest image is in the "after-edge" aligned set. Example 5 is a repetition of example 2 with largest image being an "after-edge" aligned image.

There are also four baselines that are defined only for horizontal writing-modes.

top

This baseline is the same as the "before-edge" baseline in a horizontal writing-mode and is undefined in a vertical writing mode.

text-top

This baseline is the same as the "text-before-edge" baseline in a horizontal writing-mode and is undefined in a vertical writing mode.

bottom

This baseline is the same as the "after-edge" baseline in a horizontal writing-mode and is undefined in a vertical writing mode.

text-bottom

This baseline is the same as the "text-after-edge" baseline in a horizontal writing-mode and is undefined in a vertical writing mode.

4.3. Overview of the baseline alignment process

The alignment of an element with respect to its parent is determined by three things: the scaled-baseline-table of the parent and the alignment-baseline and alignment-point of the element being aligned. Prior to alignment, the scaled-baseline-table of the parent may be shifted. The property specifications below provide the information necessary to align the parent and child elements.

There are four properties that control alignment of elements to the above set of baselines: 'dominant-baseline', 'alignment-baseline', 'baseline-shift' and 'alignment-adjust'. These properties are all independent and are designed so that typically only the specification of one of the properties is needed to achieve a particular alignment goal.

The primary baseline alignment property is the 'dominant-baseline' property. This property sets the scaled-baseline-table as a compound value with the three following components:

  1. The dominant-baseline-identifier component is the default 'alignment-baseline' to be used when aligning two inline areas.
  2. The baseline-table component specifies the positions of the baselines in the font design space coordinates. The baseline-table acts something like a musical staff; it defines particular points along the block-progression-direction to which glyphs and inline elements can be aligned.
  3. The baseline-table 'font-size' component is used to scale the positions of the baselines in that baseline table. In a scaled-baseline-table, the positions of the baselines can be adjusted by multiplying the design-space coordinate values by the baseline-table font-size.

Because the value of the 'font-family' property is a list of fonts, to insure a consistent choice of baseline-table we define the nominal font in a font list as the first font in the list for which a glyph data is available. This is the first that could contain a glyph for each character encountered. (For this definition, glyph data is assumed to be present if a font substitution is made or if the font is synthesized.) This definition insures a content independent determination of the font and baseline table that is to be used.

For convenience, the specification will sometimes refer to the baseline identified by the dominant-baseline-identifier component of the "dominant-baseline" property as the "dominant baseline" (in an abuse of terminology).

The model also assumes that each glyph has an 'alignment-baseline' value which specifies the baseline with which the glyph is to be aligned. (The 'alignment-baseline' is called the "Baseline Tag" in the OpenType baseline-table description.) The initial value of the 'alignment-baseline' property uses the baseline identifier associated with the given glyph. Alternate values for 'alignment-baseline' can be useful for glyphs such as a "*" which are ambiguous with respect to script membership.

The model assumes that the font from which the glyph is drawn also has a baseline table, the font baseline-table. This baseline table has offsets in units-per-em from the (0,0) point to each of the baselines the font knows about. In particular, it has the offset from the glyph's (0,0) point to the baseline identified by the 'alignment-baseline'.

The offset values in the baseline-table are in "design units" which means fractional units of the EM. CSS calls these "units-per-em". Thus, the current 'font-size' is used to determine the actual offset from the dominant baseline to the alternate baselines.

The glyph is aligned so that its baseline identified by its 'alignment-baseline' is aligned with the baseline with the same name from the dominant baseline-table.

The offset from the dominant baseline of the parent to the baseline identified by the 'alignment-baseline' is computed using the dominant baseline-table and dominant baseline-table font-size. The font baseline-table and font-size applicable to the glyph are used to compute the offset from the identified baseline to the (0,0) point of the glyph. This second offset is subtracted from the first offset to get the position of the (0,0) point in the shift direction. Both offsets are computed by multiplying the baseline value from the baseline-table times the appropriate font-size value.

If the 'alignment-baseline' identifies the dominant baseline, then the first offset is zero and the glyph is aligned with the dominant baseline; otherwise, the glyph is aligned with the chosen alternate baseline.

The third baseline alignment property is the 'baseline-shift' property. Like the properties other than the "dominant-baseline" property, this property does not change the baseline-table or the baseline-table font-size. It does shift the whole baseline table of the parent element so that when an inner inline element is aligned to one of the parents baselines, the position of the inner inline element is shifted.

The fourth alignment property is the 'alignment-adjust' property. This property is primarily used for replaced elements. The "alignment-adjust" property allows the author to assign where, on the start-edge of the object, the alignment point for that element lies.

For alignment purposes, the margins are added to the replaced elements dimensions.

In addition to the following definition of these properties, an informative appendix: B provides usage examples of these properties.

4.4. Dominant baseline: the 'dominant-baseline' property

Name: | dominant-baseline
Value: | auto | use-script | no-change | reset-size | alphabetic | hanging | ideographic | mathematical | central | middle | text-after-edge | text-before-edge
Initial: | auto
Applies to: | inline-level elements (but see prose)
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified value (except for initial and inherit)

The 'dominant-baseline' property is used to determine or re-determine a scaled-baseline-table. A scaled-baseline-table is a compound value with three components:

  • a baseline-identifier for the dominant baseline; it can be qualified as the 'dominant' baseline-identifier (or 'dominant baseline' in short); the baseline-identifier is basically an 'alignment-baseline' value.
  • a derived baseline-table which contains definition for additional baseline-identifiers related to various scripts,
  • and a baseline-table font-size.

Some values of the property re-determine all three values; other only reestablish the baseline-table font-size. Values for the property have the following meaning:

auto
If this property occurs on a block or inline-block element, then the user agent behavior depends on the value of the 'script' property. If the value of the script property is 'auto, the 'auto' value is equivalent to 'alphabetic' for horizontal 'writing-mode' values and 'central' for vertical 'writing-mode' values. If the value of the script property is other than 'auto', the 'auto' value is equivalent to 'use-script'
Otherwise, if this property occurs on an inline-level element, then the baseline-identifier and the baseline-table components remain the same as those of the parent element. The baseline-table font-size also remains the same as the parent's one, unless the computed 'baseline-shift' value actually shifts the baseline; then the baseline-table font-size is set to the value of the 'font-size' property on this element. If there is no parent element, the dominant-baseline components are set as for the block elements.
use-script
The dominant baseline-identifier is set using the computed value of the 'script' property. The 'writing-mode' value, whether horizontal or vertical is used to select the baseline-table that correspond to that baseline-identifier. The baseline-table font-size component is set to the value of the 'font-size' property on this element.
no-change
The dominant baseline-identifier, the baseline-table and the baseline-table font-size remain the same as that of the parent.
reset-size
The dominant baseline-identifier and the baseline table remain the same, but the baseline-table font-size is changed to the value of the 'font-size' property on this element. This re-scales the baseline table for the current 'font-size'.
alphabetic
The dominant baseline-identifier is set to the 'alphabetic' baseline, the derived baseline-table is constructed using the 'alphabetic' baseline-table in the nominal font, and the baseline-table font-size is changed to the value of the 'font-size' property on this element. (The 'alphabetic' baseline is the standard baseline for Roman scripts.)
hanging
The dominant baseline-identifier is set to the 'hanging' baseline, the derived baseline- table is constructed using the 'hanging' baseline-table in the nominal font, and the baseline-table font-size is changed to the value of the 'font-size' property on this element.
ideographic
The dominant baseline-identifier is set to the 'ideographic' baseline, the derived baseline- table is constructed using the 'ideographic' baseline-table in the nominal font, and the baseline-table font-size is changed to the value of the 'font-size' property on this element.
mathematical
The dominant baseline-identifier is set to the 'mathematical' baseline, the derived baseline- table is constructed using the 'mathematical' baseline-table in the nominal font, and the baseline-table font-size is changed to the value of the 'font-size' property on this element.
central
The dominant baseline-identifier is set to be 'central'. The derived baseline-table is constructed from the defined baselines in a baseline-table in the nominal font. That font baseline-table is chosen using the following priority order of baseline-table names: 'ideographic', 'alphabetic', 'hanging' and 'mathematical'. The baseline-table is changed to the value of the 'font-size' property on this element.
middle
The dominant baseline-identifier is set to be 'middle'. The derived baseline-table is constructed from the defined baselines in a baseline-table in the nominal font. That font baseline-table is chosen using the following priority order of baseline-table names: 'alphabetic', 'ideographic', 'hanging' and 'mathematical'. The baseline-table is changed to the value of the 'font-size' property on this element.
text-after-edge
The dominant baseline-identifier is set to be 'text-after-edge'. The derived baseline-table is constructed from the defined baselines in a baseline-table in the nominal font. That font baseline-table is chosen using the following priority order of baseline-table names: 'alphabetic', 'ideographic', 'hanging' and 'mathematical'. The baseline-table is changed to the value of the 'font-size' property on this element.
text-before-edge
The dominant baseline-identifier is set to be 'text-before-edge'. The derived baseline-table is constructed from the defined baselines in a baseline-table in the nominal font. That font baseline-table is chosen using the following priority order of baseline-table names: 'alphabetic', 'ideographic', 'hanging' and 'mathematical'. The baseline-table is changed to the value of the 'font-size' property on this element.

Note: Computed baselines do not (necessarily) choose a defining baseline table from the nominal font. The expected baseline-tables that a font would have are those that correspond to the defined baselines. The catch is that the positions of the defined baselines -- the 'hanging', 'alphabetic', 'mathematical' and 'ideograph' baselines -- can be specified differently for different choices of which of these baselines is dominant. That is, the absolute value of the offset of an alphabetic baseline from the ideographic baseline in ideographic text may be different from the offset of the ideographic baseline from the alphabetic baseline in alphabetic text. Therefore, it matters which baseline-table from the nominal font is used for the defined baselines.

If there is no baseline-table in the nominal font or if the baseline-table lacks an entry for the desired baseline, then the user agent may use heuristics to determine the position of the desired baseline.

4.5. Aligning the alignment point of an element: the 'alignment-baseline' property

Name: | alignment-baseline
Value: | baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical
Initial: | baseline
Applies to: | inline-level elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified value (except for initial and inherit)

This property specifies how an inline-level element is aligned with respect to its parent. That is, to which of the parent's baselines the alignment point of this element is aligned. Unlike the 'dominant-baseline' property the 'alignment-baseline' property has no effect on its children dominant-baselines.

Note: The 'alignment-adjust' property specifies how the alignment point is determined and defaults to the baseline with the same name as the computed value of the alignment-baseline property.

Except for 'use-script', all baseline values refer to the respective baseline-identifier components of the dominant-baseline of the parent, and glyphs within the element are aligned similarly to the element itself. The description for 'use-script' covers these points specifically. The property values have the following meanings:

baseline
The alignment-point of the element being aligned is aligned with the dominant baseline of the parent.
use-script
If the element 'script' property value is 'auto', the alignment point of each glyph is aligned with the baseline-identifier of the script to which the glyph belongs. If the element 'script' property value is other than 'auto', the alignment point of each glyph is aligned with the baseline-identifier specified by the 'script' property. The baseline-identifier position is determined by using the relevant information related to the parent element dominant-baseline set. The alignment point of the element itself is aligned as for the 'baseline' value.
before-edge
The alignment point of the box is aligned with the 'before-edge' baseline of the line box.
text-before-edge
The alignment-point of the element being aligned is aligned with the 'text-before-edge' baseline of the parent.
after-edge
The alignment point of the box is aligned with the 'after-edge' baseline of the line box.
text-after-edge
The alignment-point of the element being aligned is aligned with the 'text-after-edge' baseline of the parent.
central
The alignment point of the box is aligned with the 'central' baseline of the parent.
middle
The alignment point of the box is aligned with the 'middle' baseline of the parent.
ideographic
The alignment-point of the element being aligned is aligned with the 'ideographic' baseline of the parent.
alphabetic
The alignment-point of the element being aligned is aligned with the lower baseline of the parent.
hanging
The alignment-point of the element being aligned is aligned with the hanging baseline of the parent.
mathematical
The alignment-point of the element being aligned is aligned with the mathematical baseline of the parent.

The values: before-edge, text-before-edge, after-edge and text-after-edge all work relatively to the writing-mode property values. For example 'before-edge' means 'top' in an horizontal writing mode and 'right' in a vertical writing mode.

Note. The reason why 'baseline' is the initial value instead of 'use-script' (called 'auto' in the similar XSL property) has to do with the fact that most fonts today are designed with an alignment point located at the 'alphabetical' level, even for glyphs belonging to non Latin scripts. User agents have to deal with that constraint, and therefore they use the 'baseline' value as initial.

4.6. Setting the alignment point: the 'alignment-adjust' property

Name: | alignment-adjust
Value: | auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | <percentage> | <length>
Initial: | auto
Applies to: | inline-level elements
Inherited: | no
Percentages: | refers to the 'line-height' of the element
Media: | visual
Computed value: | see text

The 'alignment-adjust' property allows more precise alignment of elements, such as graphics, that do not have a baseline-table or lack the desired baseline in their baseline-table. With the 'alignment-adjust' property, the position of the baseline identified by the 'alignment-baseline' can be explicitly determined. It also determines precisely the alignment point for each glyph within a textual element. The user agent should use heuristics to determine the position of a non existing baseline for a given element.

Values for the property have the following meaning:

auto
For each glyph corresponding to textual information within the element, the alignment-point is the intersection of the start-edge of the glyph box and the block-progression-direction position of the alignment point from the font. Padding, border or margin do not affect that alignment point. The alignment point of the inline-level element itself is at the intersection of the start-edge of the first inline box and the baseline identified by the 'alignment-baseline' property if this baseline exists in the baseline-table for the element dominant-baseline. If that specific baseline does not exist, the user agent may use heuristics to determine where that missing baseline would be. For other inline box content like images, the user agent will use heuristics to determine the position of the alignment point. For example when the resulting baseline is 'alphabetic' or 'ideographic', it is expected that the alignment point will be at the intersection of the start-edge and the after-edge of the inline box, including its respective margin. If the resulting baseline is 'hanging', the intersection of the start-edge and the before-edge of the inline box, including its respective margin should be used instead.
When the 'alignment-baseline' property is set to either 'after-edge' or 'before-edge', the 'alignment-adjust: auto' value is equivalent to 'after-edge' or 'before-edge' respectively.
baseline
The alignment point is at the intersection of the start-edge of the element and the dominant-baseline of the element.
before-edge
The alignment point is at the intersection of the start-edge of the element and the before-edge of the extended inline box of the element. This may include or not the line-height of the element, depending on the line-stacking-strategy.
text-before-edge
The alignment point is at the intersection of the start-edge of the element and the 'text-before-edge' baseline of the element.
central
The alignment point is at the intersection of the start-edge of the element and the 'central' baseline of the element.
middle
The alignment point is at the intersection of the start-edge of the element and the 'middle' baseline of the element.
after-edge
The alignment point is at the intersection of the start-edge of the element and the after-edge of the extended inline box of the element. This may include or not the line-height of the element, depending on the line-stacking-strategy.
text-after-edge
The alignment point is at the intersection of the start-edge of the element and the 'text-after-edge' baseline of the element.
ideographic
The alignment point is at the intersection of the start-edge of the element and the 'ideographic' baseline of the element.
alphabetic
The alignment point is at the intersection of the start-edge of the element and the 'alphabetic' baseline of the element.
hanging
The alignment point is at the intersection of the start-edge of the element and the 'hanging' baseline of the element.
mathematical
The alignment point is at the intersection of the start-edge of the element and the 'mathematical' baseline of the element.
<percentage>
The computed value of the property is this percentage multiplied by the computed 'line-height' of the element. The alignment point is on the start-edge of the inline box. Its position along the start-edge relative to the intersection of the dominant-baseline and the start-edge is offset by the computed value. The offset is opposite to the shift-direction (positive value) or in the shift-direction (negative value). A value of '0%' makes the dominant-baseline the alignment point.
<length>
The alignment-point is on the start-edge of the inline box. Its position along the start-edge relative to the intersection of the dominant-baseline and the start-edge is offset by the <length> value. The offset is opposite to the shift-direction (positive value) or in the shift-direction (negative value). A value of '0cm' makes the dominant-baseline the alignment point.

4.7. Repositioning the dominant baseline: the 'baseline-shift' property

Name: | baseline-shift
Value: | baseline | sub | super | <percentage> | <length>
Initial: | baseline
Applies to: | inline-level elements
Inherited: | no
Percentages: | refers to the 'line-height' of the parent element
Media: | visual
Computed value: | see text

The 'baseline-shift' property allows repositioning of the dominant-baseline relative to the dominant-baseline. The shifted object might be a sub- or superscript. Within the shifted element, the whole baseline table is offset; not just a single baseline. For sub- and superscript, the amount of offset is determined from the nominal font of the parent.

Values for the property have the following meaning:

baseline
There is no baseline shift; the dominant baseline remains in its original position.
sub
The dominant baseline is shifted to the default position for subscripts. The offset for this position is determined by the font data for the parent nominal font as adjusted by the dominant baseline-table font-size of the parent element. If there is no applicable font data the User Agent may use heuristic to determine the offset.
super
The dominant baseline is shifted to the default position for superscripts. The offset for this position is determined by the font data for the parent nominal font as adjusted by the dominant baseline-table font-size of the parent element. If there is no applicable font data the User Agent may use heuristic to determine the offset.
<percentage>
The computed value of the property is this percentage multiplied by the computed 'line-height' of the parent element. The dominant-baseline is shifted in the shift-direction (positive value) or opposite to the shift-direction (negative value) of the parent area by the computed value. A value of '0%' is equivalent to 'baseline'.
<length>
The dominant-baseline is shifted in the shift-direction (positive value) or opposite to the shift-direction (negative value) of the parent area by the <length> value. A value of '0cm' is equivalent to 'baseline'.

Note. Although it may seem that 'baseline-shift' and 'alignment-adjust' properties are doing the same thing, there are important differences. For 'alignment-adjust' the percentage values refer to the 'line-height' of the element being aligned. For 'baseline-shift the percentage values refer to the 'line-height' of the parent element. Similarly, it is the 'sub' and 'super' offsets of the parent that are used to align the shifted baseline rather than the 'sub' and 'super' offsets of the element being positioned. To ensure a consistent sub- or superscript position, it makes more sense to use the parent as the reference rather than the subscript element which may have a changed "line-height" due to "font-size" changes in the sub- or superscript element.
Using the "alignment-adjust" property is more suitable for positioning elements, such as graphics, that have no internal textual structure. Using the "baseline-shift" property is intended for sub- and superscripts where the positioned element may itself be textual. The baseline-shift provides a way to define a specific baseline offset other than the named offsets that are defined relative to the dominant-baseline. In addition, having "baseline-shift" makes it easier for a tool to generate the relevant properties; many formatting programs already have a notion of baseline shift.

POWERED BY HeroNote

4.8. Vertical alignment: the 'vertical-align' shorthand baseline alignment property

Name: | vertical-align
Value: | auto | use-script | baseline | sub | super | top | text-top | central | middle | bottom | text-bottom | <percentage> | <length>
Initial: | not defined for shorthand properties
Applies to: | inline-level and 'table-cell' elements
Inherited: | no
Percentages: | refers to the 'line-height' of the element itself
Media: | visual
Computed value: | see text

This property affects the vertical positioning of the inline boxes generated by an inline-level element inside a line box. The following values only have meaning with respect to a parent inline-level element, or to a parent block-level element, if that element generates anonymous inline boxes; they have no effect if no such parent exists.

Note. Values of this property have slightly different meanings in the context of tables. Please consult the section on table height algorithms for details.

auto
Align the dominant baseline of the parent box with the equivalent, or heuristically reconstructed, baseline of the element inline box. If the element doesn't have a baseline, align the bottom of the inline box, including its margin with the parent's dominant baseline. If there is no parent or if there is a change of flow orientation between this element and its parent, the dominant baseline is set to 'alphabetic' for horizontal flow and 'central' for vertical flow.
use-script
Align the script preferred baseline of the element (determined by the computed script value) with the equivalent baseline of the parent element.
baseline
Align the 'alphabetic' baseline of the element with the 'alphabetic' baseline of the parent element. If the inline element doesn't have an 'alphabetic' baseline, align the bottom of the box, including its margin for replaced elements, with the parent's 'alphabetic' baseline. The dominant baseline is set to 'alphabetic' if there is no parent or if there is a flow orientation change between this element and its parent, otherwise it is set to 'no-change'.
central
Align the 'central' baseline of the inline element with the central baseline of the parent.
middle
Align the 'middle' baseline of the inline element with the middle baseline of the parent.
sub
Lower the baseline of the box to the proper position for subscripts of the parent's box. (This value has no effect on the font size of the element's text.)
super
Raise the baseline of the box to the proper position for superscripts of the parent's box. (This value has no effect on the font size of the element's text.)
text-top
Align the top of the box with the before-edge of the parent element's font.
text-bottom
Align the bottom of the box with the after-edge of the parent element's font.
<percentage>
Raise (positive value) or lower (negative value) the box by this distance (a percentage of the computed 'line-height' of the element). The value '0%' means the same as 'baseline'.
<length>
Raise (positive value) or lower (negative value) the box by this distance. The value '0cm' means the same as 'baseline'.

The remaining values refer to the line box in which the generated box appears:

top
Align the before edge of the extended inline box with the before-edge of the line box.
bottom
Align the after edge of the extended inline box with the after-edge of the line box.

The 'vertical-align' property values affect the baseline alignment properties for which it is a shorthand in the following manner:

vertical-align value | alignment-baseline | alignment-adjust | baseline-shift | dominant-baseline
auto | baseline | auto | baseline | auto
use-script | use-script | auto | auto | auto
baseline | baseline | auto | baseline | alphabetic (if no parent or different flow from parent) no-change (otherwise)
sub | baseline | auto | sub | auto
super | baseline | auto | super | auto
top | before-edge | auto | baseline | auto
text-top | text-before-edge | auto | baseline | auto
central | central | auto | baseline | auto
middle | middle | auto | baseline | auto
bottom | after-edge | auto | baseline | auto
text-bottom | text-after-edge | auto | baseline | auto
<percentage> | baseline | <percentage> | baseline | auto
<length> | baseline | <length> | baseline | auto

4.9. Inline box alignment: the 'inline-box-align' property

Name: | inline-box-align
Value: | initial | last | <integer>
Initial: | last
Applies to: | inline-block-level elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified value (except for initial and inherit)

The 'inline-box-align' property determines which line of a multi-line inline block align with the previous and next inline elements within a line. The alignment strategy for the inline lock itself (i.e. the definition of it alignment point and which parent baseline should be used for the alignment) is determined by the inline block element baseline alignment properties applicable to the line being used for the alignment. This property has no effect for single line inline block. Possible values:

initial
Use the initial line of the inline block element for alignment purpose.
last
Use the last line of the inline block element for alignment purpose.
<integer>
Use nth line (as determined by the integer value) of the inline block element for alignment purpose.

5. Initial line and Drop initial

5.1. Initial line

On a block element containing inline elements, the initial line is very often presented differently. For example it may use a difference typeface, a color, font-size or even casing (like all uppercase). The presentation of that initial line can be controlled by applying a limited set of style properties to the ::first-line pseudo element. Only the following properties can be applied to the ::first-line pseudo elements:

  • font properties
  • color properties
  • background properties
  • text decoration properties
  • baseline alignment properties
  • 'word-spacing'
  • 'letter-spacing'
  • 'line-height' (may be ignored depending on the block line-stacking strategy)
  • 'text-shadow'
  • 'clear'

Although there is no properties only applicable to ::first-line pseudo elements, in essence the 'text-indent' property which is applied to 'block-level' elements is in fact only effective on the first line of the block element.

5.2. Drop Initial overview

Drop initial is a typographic effect emphasizing the initial letter(s) of a block element with a presentation similar to a 'floated' element. It can be described as the combination of the following effects:

  • For the purpose of drop initial, an initial letter has two alignment points: an 'after' alignment point and a 'before' alignment point. (For writing-mode:lr-tb, 'after' corresponds to bottom and 'before' to 'top').

  • The 'after' alignment point connects with one of the alignment point of the nth line of the block element of which the initial letter is part of. The value 'n' is the number of lines by which the initial letter is dropped. That connection point is called the primary connection point. The union of the two alignment lines makes a connection line.

  • If no drop initial size is explicitly provided, there is a secondary connection point where the 'before' alignment points connects with one of the alignment point of the initial line. In that case the initial letter is totally sunken.

  • If a drop initial size is provided, there is no secondary connection point as it would result otherwise in an over constraint situation. In that case the initial letter may not be totally sunken, especially if the size is provided in 'line' unit with a number larger than the drop.

  • The values provided above result in the creation of an 'ink box' which is filled by the initial letter. Depending on the selected alignment points, part of the glyphs may bleed beyond the ink box.

  • The character content of the drop initial influences greatly how the drop initial letters are best aligned with the rest of the block element content.

The CSS mechanism to 'select' the drop initial content is the ::first-letter pseudo element. The first letter is defined as including all starting punctuation characters (defined in Unicode as 'open' (Ps), 'close' (Pe) and 'other' (Po), if any, followed by the first non-punctuation character cluster. A character cluster may be a single character, a combining sequences (base character followed by combining characters) or a stacked set of characters (like in Thai).

Only the following properties can be applied to the ::first-letter pseudo elements:

  • font properties
  • color properties
  • background properties
  • text decoration properties
  • baseline alignment properties (only if 'float' is 'none')
  • 'text-transform'
  • 'letter-spacing'
  • 'line-height' (may be ignored depending on the block line-stacking strategy)
  • margin properties
  • padding properties
  • border properties
  • 'float'
  • text-shadow
  • 'clear'
  • all properties described in this section (drop-initial-...)

In addition, one property: 'text-indent' although applying to block-level elements is in fact effective on its first line of text and has therefore an influence on the indentation of the first-letter versus the start edge of the containing block. Using the 'text-indent' allows the correction of optical effect (like uppercase 'O') or even pushing the starting piece of the initial letter in a 'virtual' margin.

Editor's note: Additional drop initial features are desirable but are not described in this specification:

  • bleeding between the drop initial and its related block content,

  • tight wrap between the drop initial and its related block content

  • multiple letter with author control (not possible with ::first-letter)

  • multiple size and alignment within the drop initial (required for French opening guillemet)

Some of these features (multiple letter and size) could be achieved by introducing a new display value, like 'display: drop-initial' which when applied to an inline element part of the first line could make it behave like a drop initial inline element.

The following figure shows first a simple case of a three line drop initial, and second a case of a two line drop initial but with a three line size initial letter.

simple drop caps

Typical drop initial cases: sunken cap and partially raised cap

The bottom horizontal line in the first example shows the alignment between the baseline of the initial letter and the baseline of the third line of its block element. The primary connection point occurs at the intersection of these baselines between the two boxes (the third line box and the initial letter box). The top horizontal line shows a connection point between the top of the ink of the initial letter and the text-before-edge baseline of the initial line. Alternatively, instead of the text-before-edge baseline, a new computed alignment could be used which correspond loosely to the maximum caps-height of the initial line.

Typically the ink of drop initial characters 'fills' the space between the baseline and the text-before-edge, therefore 'taller' characters are processed accordingly. This is shown in the first two pictures of the following figure, using first an accentuated letter, and then a letter without accent.

drop caps showing case with and without accent

Drop initial with accent and without accent

The third picture shows a more correct effect with the acute accent drawn in the upper padding area. This effect is realized by having the secondary connection point between the initial letter caps height and the maximum caps height of the initial line.

Typically characters are stretched in both direction to fill the space between the primary and secondary connection lines (in the absence of an explicit drop initial size). Even if the character has no 'ink' at the primary connection line, the stretching is performed as if there were a 'virtual' point at that level. The following figure demonstrates the effect for the hyphen-minus character. The other two characters demonstrate the variable stretching made by the drop initial effect.

drop cap with period, hyphen and exclamation point

Drop initial with period, hyphen and exclamation point

For characters that have only ink 'after' (below) their baseline there is really no good strategy. It may be better to use the font EM square as reference for symbols that have no ink at the primary connection line.

Some characters are always expected to be shown as if using their full EM square, even in drop initial situation. For example, this is the case for all ideograms and related characters like the Japanese Kana characters. The following figure shows how the ink of the character representing the number one in CJK (middle picture) is not stretched to hit the top of the text-before-edge of the initial line, but is instead stretched following the same ratio as the character in the left picture. The picture on the right shows that drop initial can also be used in vertical flow.

drop cap with ideographs

Drop initial with ideographic characters

Drop initial characters can be aligned using a variety of baselines for the drop initial alignment point used for the primary connection point. The examples above used the alphabetic and the ideographic baselines. The following figures compares the usage of the text-after-edge baseline (picture on the left) and the alphabetic baseline (picture on the right). Note that when the alphabetic baseline is used for characters that have ink below the baseline, the actual drop initial effect may occur through many more lines to accommodate the text-after-edge constraint.

drop cap with lowercase letters

Drop initial with lowercase characters

drop cap with uppercase q

Drop initial with uppercase character with descender

The drop initial effect may also be used for writing systems which use different alignment strategies. For example, in Devanagari the hanging baseline may be preferred. In that case the primary connection point connects the text-after-edge of the initial letter with the text-after-edge of the nth line, but the secondary connection point connects the hanging baselines of the initial letter and the initial line. This is shown in the following figure:

drop cap with devanagari

Drop initial with hanging devanagari characters

The drop initial effect is typically based on a number of lines, i.e. the combined line-height adjusted by the alignment strategies for the connection lines is used to determine the default size of the drop initial character. However there is a potential circular issue as the activation of the effect modifies the content of the lines and therefore may affect their line-height. The recommended strategy is to determine the drop initial character size using the initial combined line height and to possibly stretch the character along the new baseline if the combined line height is modified by the drop initial effect. The following figure shows the initial text on the left, an incorrect drop initial effect in the middle (no stretch applied) and a correct effect on the right (stretch applied).

drop cap with variable line heights

Drop initial with variable line heights

5.3. Sizing drop initial, the 'drop-initial-size' and the 'drop-initial-value' properties

Name: | drop-initial-value
Value: | initial | <integer>
Initial: | initial
Applies to: | ::first-letter pseudo element
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified values (except for initial and inherit)

The 'drop-initial-value' property is the basic property that activates a drop-initial effect. By providing a value different than 'initial or '1', the primary connection point is moved after the initial line. Possible values:

initial
The drop initial letter is aligned on the initial line
<integer>
The drop initial letter is sunken to the nth line (as determined by the integer value).
Name: | drop-initial-size
Value: | auto | <line> | <length> | <percentage>
Initial: | auto
Applies to: | ::first-letter pseudo element
Inherited: | no
Percentages: | refer to combined line height size as provided by drop-initial-value
Media: | visual
Computed value: | specified values (except for initial and inherit)

The 'drop-initial-size' property controls the partial sinking of the initial letter. Using any other value than 'auto' removes the secondary connection line constraint. Possible values:

auto
The drop initial letter is sized according to the constraints created by the the ink filling strategy and the two connection lines.
<line>
The drop initial letter is sized using the combined line height of the nth lines (as determined by the line value). The letter may be stretched on one dimension if the line height of each line is variable to avoid circular issues.
<length>
The drop initial letter is sized using the length value.
<percentage>
The drop initial letter is sized relatively to the combined line height of the n lines determined by the 'drop-initial-value' property value.

5.4. Aligning drop initial: the 'drop-initial-before-align', 'drop-initial-before-adjust', 'drop-initial-after-align' and 'drop-initial-after-adjust' properties

Name: | drop-initial-after-align
Value: | <'alignment-baseline'>
Initial: | baseline
Applies to: | ::first-letter pseudo element
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified values (except for initial and inherit)

The 'drop-initial-after-align' property determines which alignment line within the nth line box (n being defined by the 'drop-initial-value' property) is used at the primary connection point with the initial letter box. The values are the same as the 'alignment-baseline' property values.

Name: | drop-initial-after-adjust
Value: | central | middle | after-edge | text-after-edge | ideographic | alphabetic | mathematical | <percentage> | <length>
Initial: | text-after-edge
Applies to: | ::first-letter pseudo element
Inherited: | no
Percentages: | refer to combined line height size as provided by drop-initial-value
Media: | visual
Computed value: | specified values (except for initial and inherit)

The 'drop-initial-after-adjust' property sets the alignment point of the drop initial for the primary connection point. Possible values:

central
The alignment point is at the intersection of the end-edge of the element and the 'central' baseline of the element.
middle
The alignment point is at the intersection of the end-edge of the element and the 'middle' baseline of the element.
after-edge
The alignment point is at the intersection of the end-edge of the element and the 'after-edge' of the extended inline box of the element. This may include or not the line-height of the element, depending on the line-stacking-strategy.
text-after-edge
The alignment point is at the intersection of the end-edge of the element and the 'text-after-edge' baseline of the element.
ideographic
The alignment point is at the intersection of the end-edge of the element and the 'ideographic' baseline of the element.
alphabetic
The alignment point is at the intersection of the end-edge of the element and the 'alphabetic' baseline of the element.
hanging
The alignment point is at the intersection of the end-edge of the element and the 'hanging' baseline of the element.
mathematical
The alignment point is at the intersection of the end-edge of the element and the 'mathematical' baseline of the element.
<percentage>
The computed value of the property is this percentage multiplied by the computed 'line-height' of the element. The alignment point is on the end-edge of the inline box and is offset from the after-edge by the computed value. A value of '0%' makes the text-after-edge the alignment point.
<length>
The alignment-point is on the end-edge of the inline box. Its position along the end-edge is offset from the after-edge by the <length> value. A value of '0cm' makes the text-after-edge the alignment point.
Name: | drop-initial-before-align
Value: | caps-height | <'alignment-baseline'>
Initial: | caps-height
Applies to: | ::first-letter pseudo element
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified values (except for initial and inherit)

The 'drop-initial-before-align' property determines which alignment line within the initial line box is used at the secondary connection point with the initial letter box. This property is only effective is the value of the 'drop-initial-size' property is 'auto'. Possible values:

caps-height
The caps-height alignment line is used.
<'alignment-baseline'>
The values are the same as the 'alignment-baseline' property values.
Name: | drop-initial-before-adjust
Value: | before-edge | text-before-edge | central | middle | hanging | mathematical | <percentage> | <length>
Initial: | text-before-edge
Applies to: | ::first-letter pseudo element
Inherited: | no
Percentages: | refer to combined line height size as provided by drop-initial-value
Media: | visual
Computed value: | specified values (except for initial and inherit)

The 'drop-initial-before-adjust' property sets the alignment point of the drop initial for the secondary connection point. This property is only effective is the value of the 'drop-initial-size' property is 'auto'. Possible values:

before-edge
The alignment point is at the intersection of the end-edge of the element and the 'before-edge' of the extended inline box of the element. This may include or not the line-height of the element, depending on the line-stacking-strategy.
text-before-edge
The alignment point is at the intersection of the end-edge of the element and the 'text-before-edge' baseline of the element.
central
The alignment point is at the intersection of the end-edge of the element and the 'central' baseline of the element.
middle
The alignment point is at the intersection of the end-edge of the element and the 'middle' baseline of the element.
hanging
The alignment point is at the intersection of the end-edge of the element and the 'hanging' baseline of the element.
mathematical
The alignment point is at the intersection of the end-edge of the element and the 'mathematical' baseline of the element.
<percentage>
The computed value of the property is this percentage multiplied by the computed 'line-height' of the element. The alignment point is on the end-edge of the inline box and is offset from the text-before-edge by the computed value. A value of '0%' makes the text-before-edge the alignment point.
<length>
The alignment-point is on the end-edge of the inline box. Its position along the end-edge is offset from the text-before-edge by the <length> value. A value of '0cm' makes the text-before-edge the alignment point.

6. Properties index

In addition to the specified values, all properties take the initial and inherit values

Property | Values | Initial | Applies to | Inh. | Percentages | Media
alignment-adjust | auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | <percentage> | <length> | auto | inline-level elements | no | refers to the 'line-height' of the element | visual
alignment-baseline | baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical | baseline | inline-level elements | no | N/A | visual
baseline-shift | baseline | sub | super | <percentage> | <length> | baseline | inline-level elements | no | refers to the 'line-height' of the parent element | visual
dominant-baseline | auto | use-script | no-change | reset-size | alphabetic | hanging | ideographic | mathematical | central | middle | text-after-edge | text-before-edge | auto | inline-level elements (but see prose) | no | N/A | visual
drop-initial-after-adjust | central | middle | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | <percentage> | <length> | text-after-edge | ::first-letter pseudo element | no | N/A | visual
drop-initial-after-align | <'alignment-baseline'> | baseline | ::first-letter pseudo element | no | N/A | visual
drop-initial-before-adjust | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | hanging | mathematical | <percentage> | <length> | text-before-edge | ::first-letter pseudo element | no | N/A | visual
drop-initial-before-align | caps-height | <'alignment-baseline'> | caps-height | ::first-letter pseudo element | no | N/A | visual
drop-initial-size | auto | <line> | <length> | <percentage> | auto | ::first-letter pseudo element | no | refers to combined line height size as provided by drop-initial-value | visual
drop-initial-value | initial | <integer> | initial | ::first-letter pseudo element | no | N/A | visual
inline-box-align | initial | last | <integer> | last | inline-block-level elements | no | N/A | visual
line-height | normal | number | <length> <percentage> | none | normal | all elements and generated content | yes | refer to the font size of the element itself | visual
line-stacking | <'line-stacking-strategy'> || <'line-stacking-ruby'> || <'line-stacking-shift'> | see individual properties | block-level elements | yes | N/A | visual
line-stacking-ruby | exclude-ruby | include-ruby | exclude-ruby | block-level elements | yes | N/A | visual
line-stacking-shift | consider-shifts | disregard-shifts | consider-shifts | block-level elements | yes | N/A | visual
line-stacking-strategy | inline-line-height | block-line-height | max-height | grid-height | inline-line-height | block-level elements | yes | N/A | visual
text-height | auto | font-size | text-size | max-size | auto | inline elements and parents of element with display:ruby-text | yes | N/A | visual
vertical-align | auto | use-script | baseline | sub | super | top | text-top | central | middle | bottom | text-bottom | <percentage> | <length> | not defined for shorthand properties | inline-level and 'table-cell' elements | no | refers to the 'line-height' of the element itself | visual

The following properties are mentioned in this module, but are defined elsewhere:

  • script, direction, text-align, writing-mode, see the Text module.
  • font-size, see the Fonts module.

7. Profiles

There are 3 modules defined by this chapter:

CSS1 line model:

CSS2 line model:

CSS3 line model:

The CSS1 line module is made of the following properties/values:

Name | Values | Initial | Applies to | Inherited | Percentages | Media groups
'line-height' | normal | <number> | <length> | <percentage> | normal | all elements | yes | relative to the font-size of the element itself | N/A
'vertical-align' | baseline | sub | super | top | text-top | middle | bottom | text-bottom | <percentage> | baseline | inline-level elements | no | N/A | N/A

The following table describes the CSS2 text module. Because all properties have added the 'inherit' value and have a media type, all CSS1 properties have been specified below as well. In addition, the 'vertical-align' has a new value: <length>. Properties that applies to all elements also applies to generated content. Finally, 'vertical-align' also applies to table-cell elements.

.Name | Values | Initial | Applies to | Inherited | Percentages | Media groups
'line-height' | normal | <number> | <length> | <percentage> | normal | all elements and generated content | yes | relative to the font-size of the element itself | N/A
'vertical-align' | baseline | sub | super | top | text-top | central | middle | bottom | text-bottom | <percentage> | <length> | inherit | baseline | inline-level and table-cell elements | no | N/A | visual

The CSS3 module adds the following properties:

  • Line stacking and content height: 'line-stacking-strategy', 'line-stacking-ruby', 'line-stacking-shift', 'line-stacking', 'text-height',
  • Baseline alignment: 'alignment-adjust', 'alignment-baseline', 'baseline-shift', 'dominant-baseline', 'inline-box-align',
  • Drop initial letter: 'drop-initial-size', 'drop-initial-value', 'drop-initial-after-adjust', 'drop-initial-after-align', 'drop-initial-before-adjust', 'drop-initial-before-align',

It also modifies the following properties as described:

  • 'vertical-align' has three new value: 'auto', middle and 'use-script' and has its initial value changed to 'auto'.
  • all properties take the value 'initial'.

8. Glossary

Hiragana
Japanese syllabic script, or character of that script. Rounded and cursive in appearance. Subset of the Japanese writing system, used together with kanji and katakana. In recent times, mostly used to write Japanese words when kanji are not available or appropriate, and word endings and particles. Also see Katakana.
Ideograph
A character that is used to represent an idea, word, or word component, in contrast to a character from an alphabetic or syllabic script. The most well-known ideographic script is used (with some variation) in East Asia (China, Japan, Korea,...).
Kana
Collective term for hiragana and katakana.
Katakana
Subset of the Japanese writing system consisting of phonetic characters used to represent Roman words. Also see Hiragana.
Ruby
A run of text that appears in the vicinity of another run of text and serves as an annotation or a pronunciation guide for that text.

Appendix A: Usage of baseline alignment (informative)

The following appendix shows some examples of baseline alignment, exercising the related properties .

A simple example of alignment is shown in the following figure. The figure shows the presentation of two inline elements, one inside the other. These inline elements make up the content of a line in a block where the writing-mode is "lr-tb" and the font is "Helvetica". The structure of the example is as follows:

<p><span class="outer">Apex <span class="inner">Top</span></span></p>

with the style being defined as:

p { writing-mode: lr-tb; font: Helvetica; }
span { alignment-baseline: use-script; }

The other baseline alignment initial values apply. Since a horizontal writing-mode is in use, the dominant-baseline-identifier is set to "alphabetic" and the baseline-table is taken from the nominal-font for the block in which the line appears, which, in this case, is Helvetica.

In the figure, the positions of the baselines relative to the current font size are shown as red (staff) lines. These lines are labeled with abbreviations of the names of the baselines (e.g., TBE for "text-before-edge"). The baseline identified by the dominant-baseline-identifier (A) is shown in blue. There is a break in the staff lines to separately show the inner inline element. This is not necessary for this example, but this distinction will become important in subsequent examples.

The "alignment-baseline" property is the primary control on the positioning of an inner element with respect to its parent. The initial value of the "alignment-baseline" property is "baseline". This aligns the dominant-baseline of the inner inline element with the dominant baseline of the outer inline element. This is shown by the short blue line that connects the two separated staffs (A) in the figure.

The glyphs that are in the content of the two elements are aligned based on the script to which the glyph belongs. Since this example only has Latin glyphs, they are aligned to the "alphabetic" baseline.

An inner inline element containing Latin characters aligned to an outer inline element also containing Latin characters.

In the next figure, the content of the inner inline element is in Gurmukhi, the script of the Punjabi language. The Gurmukhi syllables are read as "guru". Rather than use Unicode values for these characters, they are symbolized by placing the Latin transliteration in italic type. The structure of the example becomes (assuming the same style):

<p><span class="outer">Apex <span class="inner">guru</span></span></p>

The only change from the previous example is that the glyphs of the Gurmukhi script are aligned to the "hanging" baseline of the inner inline element. The alignment of that element itself, with respect to the outer inline element, is unchanged. The "hanging" baseline position is computed from the font-table part of the dominant-baseline set of the parent element (in this case the outer inline element which is getting itself the set from its parent, the block element).

An inner inline element containing Gurmukhi characters aligned to an outer inline element containing Latin characters.

In the next figure, fragments of the text of the previous examples make up the content of the outer inline element. The inner inline element has a change of font-size, however. The structure is:

<p><span class="outer">Apguru <span class="inner">Exji</span></span></p>

with the following style:

p { writing-mode: lr-tb; font: Helvetica; }
span { alignment-baseline: use-script; }
span.inner { font-size: .75em; }

In this example, the alignment of the inner inline element itself does not change, nor does the alignment of the smaller glyphs inside the inner element. The Latin glyphs are still aligned to the "alphabetic" baseline and the Gurmukhi glyphs, which are pronounced "ji" are aligned to the "hanging" baseline. Note also that just changing the "font-size" property did not change the baseline-table in effect in the inner inline element.

baselines and font size

The inner inline element has a reduced font-size.

The next figure is equivalent to the previous example with the Gurmukhi character replaced by ideographic characters. These are aligned to the "ideographic" baseline.

baselines and font size

The previous figure redone with ideographic glyphs instead of Gurmukhi glyphs. The EM boxes are shown for the ideograms to clarify the alignment of these glyphs.

To change the scaling of the lines of the baseline table, it is necessary to use the "dominant-baseline" property on the inner inline element. The value of "reset-size" causes the baseline-table font-size to be reset from the font-size of the element on which the "dominant-baseline" property appears. The next figure shows the effect of this, using the structure:

<p><span class="outer">Apguru <span class="inner">Exji</span></span></p>

with the following style:

p { writing-mode: lr-tb; font: Helvetica; }
span { alignment-baseline: use-script; }
span.inner { font-size: .75em; dominant-baseline: reset-size; }

The alignment of the inner inline element, with respect to the outer inline element, is still determined by aligning the dominant baselines (alphabetic). But, the baseline-table of the inner inline element has been rescaled to the font-size of the inner inline element. Hence the smaller glyphs align with each other.

The baseline-table of the inner inline element has been resized to match the font-size of the inner inline element.

But, what if it is more important that the small Gurmukhi glyphs align with the large Gurmukhi glyphs than having the Latin glyphs align. There are at least two ways to achieve this. The structure:

<p><span class="outer">Apguru <span class="inner">Exji</span></span></p>

with the following style:

p { writing-mode: lr-tb; font: Helvetica; }
span { alignment-baseline: use-script; }
span.outer {dominant-baseline: hanging }
span.inner { font-size: .75em; dominant-baseline: reset-size; }

is illustrated in the next figure. The "hanging" baseline becomes the dominant baseline and the initial value of the "alignment-baseline" property causes the (newly) dominant "hanging" baselines to be aligned as is shown by the connection of the blue baselines.

Changing the dominant baseline to the "hanging" baseline causes the inner inline element to be aligned on its parent's "hanging" baseline.

It is also possible to achieve the effect of the above figure without changing the dominant baseline. Instead it is sufficient to explicitly specify that the inner inline element is aligned on its "hanging" baseline. This is done by:

<p><span class="outer">Apguru <span class="inner">Exji</span></span></p>

with the following style:

p { writing-mode: lr-tb; font: Helvetica; }
span { alignment-baseline: use-script; }
span.inner { font-size: .75em; dominant-baseline: reset-size; alignment-baseline: hanging; }

The only change this approach would make in the above figure is to color the "hanging" baseline red and keep the "alphabetic" baseline as the (blue) dominant baseline. This baseline in the inner inline element would not (as it does not in the above figure) align with the "alphabetic" baseline in the outer inline element.

Another baseline alignment property is the "baseline-shift" property. Like the properties other than the "dominant-baseline" property, this property does not change the baseline-table or the baseline-table font-size. It does shift the whole baseline table of the parent element so that when an inner inline element is aligned to one of the parents baselines, the position of the inner inline element is shifted. This is illustrated in the next figure. The structure which creates this figure is:

<p><span class="outer">Apex <span class="inner">1ji</span></span></p>

with the following style:

p { writing-mode: lr-tb; font: Helvetica; }
span { alignment-baseline: use-script; }
span.inner { baseline-shift: super; }

Because the whole set of baseline-table staff lines are shifted to the position of the superscript baseline: it does not matter to which baseline the glyphs in the superscript are aligned. The European number "1" is aligned to the "alphabetic" baseline and the Gurmukhi syllable "ji" is aligned to the "hanging" baseline.

Using a "baseline-shift" for a superscript (or a subscript).

It is more common for the font-size of the superscript text to be smaller than the font-size of the text to which it is appended. Consider:

<p><span class="outer">Apex <span class="inner">1ji</span></span></p>

with the following style:

p { writing-mode: lr-tb; font: Helvetica; }
span { alignment-baseline: use-script; }
span.inner { baseline-shift: super; font-size: .75em; }

Because changing the font-size on a superscript (or subscript) is common, this is the one case where changing the font-size does cause the baseline-table font-size to be reset when the "dominant-baseline" property has its initial value. After the rescaling, the default alignment to the dominant baseline positions the inline element for the superscript to the dominant baseline position in the shifted baseline-table of the parent element.

Reducing the font-size of the superscript automatically resets the baseline-table size so that mixed languages in the superscript stay mutually aligned.

Acknowledgments

In additions to the authors, this specification would not have been possible without the help from:

Stephen Deach, Sujal Parikh, Grzegorz Zygmunt, Chris Wilson, David M Brown.

References

Normative references

Other references

[CSS2]
Bert Bos; Håkon Wium Lie; Chris Lilley; Ian Jacobs. Cascading Style Sheets, level 2. 1998. W3C Recommendation. URL: http://www.w3.org/TR/REC-CSS2
[CSS3-background]
Tim Boland; Bert Bos. CSS3 module: backgrounds. 19 February 2002. W3C working draft. (Work in progress.) URL: http://www.w3.org/TR/2002/WD-css3-background-20020219
[CSS3-color]
Tantek Çelik; Chris Lilley. CSS3 module: color. 5 March 2001. W3C working draft. (Work in progress.) URL: http://www.w3.org/TR/2001/WD-css3-color-20010305
[CSS3-fonts]
Michel Suignard; Chris Lilley. CSS3 module: fonts. 31 July 2001. W3C working draft. (Work in progress.) URL: http://www.w3.org/TR/2001/WD-css3-fonts-20010731
[HTML40]
Raggett, D.; Le Hors, A.; Jacobs, I.. HTML 4.0 Specification (revised). Apr 1998. W3C Recommendation. URL: http://www.w3.org/TR/1998/REC-html40-19980424
[HTML401]
Raggett, D.; Le Hors, A.; Jacobs, I.. HTML 4.01 Specification. Dec 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-html401-19991224
[ISO15924]
Code for the representation of names of scripts. International Organization for Standardization.. 1998. ISO 15924:1998. Draft International Standard
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[SVG1.0]
Various. Scalable Vector Graphics (SVG) 1.0 Specification. Sep 2001. W3C Recommendation. URL: http://www.w3.org/TR/2001/REC-SVG-20010904
[UNICODE]
The Unicode Consortium. The Unicode Standard: Version 3.1.0. Addison Wesley Longman. 2000. ISBN 0-201-61633-5. The latest version of Unicode. For more information, consult the Unicode Consortium's home page at <a href="http://www.unicode.org/">http://www.unicode.org/</a> URL: http://www.unicode.org/unicode/standard/versions/enumeratedversions.html#Unicode_3_1_0
[UTR-24]
Mark Davis. Script Names. 27 September 2001. Unicode Technical Report #24. URL: http://www.unicode.org/unicode/reports/tr24/tr24-3.html
[XHTML1.0]
Steven Pemberton; et al. XHTML 1.0: The Extensible HyperText Markup Language. Jan 2000. W3C Recommendation. URL: http://www.w3.org/TR/2000/REC-xhtml1-20000126
[XHTMLMOD]
Adams, Robert; Altheim, Murray; et al. Modularization of XHTML. Apr 2001. W3C Recommendation. URL: http://www.w3.org/TR/2001/REC-xhtml-modularization-20010410
[XML1.0]
Tim Bray; Jean Paoli; C. M. Sperberg-McQueen; Eve Maler. Extensible Markup Language (XML) 1.0 (Second Edition). Oct 2000. W3C Recommendation. URL: http://www.w3.org/TR/2000/REC-xml-20001006
[XSL1.0]
Adler, Sharon; Berglund, Anders; et al. Extensible Stylesheet Language (XSL) Version 1.0. Oct 2001. W3C Recommendation. URL: http://www.w3.org/TR/2001/REC-xsl-20011015

Changes from Previous Working Draft

New draft, but with a large piece taken out from former versions of CSS3 text and CSS2


CSS3 module- Lists

CSS3 module: Lists

W3C Working Draft 7 November 2002

This version:
http://www.w3.org/TR/2002/WD-css3-lists-20021107
Latest version:
http://www.w3.org/TR/css3-lists
Previous version:
http://www.w3.org/TR/2002/WD-css3-lists-20020220
Editors:
Ian Hickson, ian@hixie.ch
Tantek Çel&#x0131?k, Microsoft Corporation, tantekc@microsoft.com
Contributors:
Simon Montagu, AOL-TW/Netscape, smontagu@netscape.com
Daniel Yacob, yacob@geez.org
Christopher Hoess, choess@stwing.upenn.edu
Daniel Glazman, AOL-TW/Netscape, glazman@netscape.com

Copyright © 2002 W3C ® (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.

Abstract

This CSS level 3 module describes how lists are styled.

Status of this document

This document is a draft of one of the "modules" [CSS3INTRO] for the upcoming CSS3 specification. It extends, but also proposes changes to the functionality provided by the existing CSS level 2.

This document is a working draft of the CSS working group which is part of the style activity (see summary).

Comments on, and discussions of this draft can be sent on the (archived) public mailing list www-style@w3.org (see instructions). W3C Members can also send comments directly to the CSS working group.

This is a working draft and may therefore be updated, replaced or rendered obsolete by other W3C documents at any time. It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress". Its publication does not imply endorsement by the W3C membership or the CSS Working Group (members only).

To find the latest version of this working draft, please follow the "Latest version" link above, or visit the list of W3C Technical Reports.

Patent disclosures relevant to CSS may be found on the Working Group's public patent disclosure page.

This document may be available in translations in the future. The English version of this specification is the only normative version.

Table of contents

  • 1. Dependencies on other modules
  • 2. Introduction
  • 3. Declaring a List Item
  • 4. List Content: The 'list-style-type' property
    • 4.1. Glyphs
    • 4.2. Algorithmic
    • 4.3. Numeric
    • 4.4. Alphabetic
    • 4.5. Symbolic
    • 4.6. Non-repeating
    • 4.7. Unsupported list styles
  • 5. List Content: The 'list-style-image' property
  • 6. List Content: Generating the computed value of the 'content' property
  • 7. Marker Position: The 'list-style-position' property
  • 8. The 'list-style' shorthand property
  • 9. Markers: The ::marker pseudo-element
  • 10. Profiles
  • 11. Sample style sheet for HTML 4.0
  • Acknowledgments
  • Changes From CSS2
  • References
    • Normative references
    • Other references
  • Index

1. Dependencies on other modules

This CSS3 module depends on the following other CSS3 modules:

  • CSS3 module: syntax [CSS3SYN]
  • CSS3 module: values and units [CSS3VAL]
  • CSS3 module: selectors [SELECT]
  • CSS3 module: generated and replaced content [CSS3GENCON] (counters, the 'content' property)
  • CSS3 module: block box model [CSS3BOX]
  • CSS3 module: inline box model [CSS3LINE]

2. Introduction

The list model in this module differs in some important ways from the list model in CSS2, specifically in its handling of markers. Implementation experience suggested the CSS2 model overloaded the ::before and ::after pseudo-elements with too much behavior, while at the same time introducing new properties when existing properties were sufficient.

Most block-level elements in CSS generate one principal block box. In this module, we discuss two CSS mechanisms that cause an element to have an associated marker: one method associates one principal block box (for the element's content) with a separate marker box (for decoration such as a bullet, image, or number), and the other inserts a marker box into the principal box. Unlike :before and :after content, the marker box cannot affect the position of the principal box, whatever the positioning scheme.

For instance, the following example illustrates how markers may be used to add parentheses around each numbered list item. This HTML application and style sheet:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
 <HEAD>
  <TITLE>Creating a list with markers</TITLE>
  <STYLE type="text/css">
   LI::marker { content: "(" counter(list-item, lower-roman) ")"; }
   LI { display: list-item; }
  </STYLE>
 </HEAD>
 <BODY>
  <OL>
   <LI> This is the first item. </LI>
   <LI> This is the second item. </LI>
   <LI> This is the third item. </LI>
  </OL>
 </BODY>
</HTML>

should produce something like this:

  (i) This is the first item.
 (ii) This is the second item.
(iii) This is the third item.

With descendant selectors and child selectors, it's possible to specify different marker types depending on the depth of embedded lists.

A future release of this module will probably include ways to render tree lists.

3. Declaring a List Item

To declare a list item, the 'display' property should be set to 'list-item'. This, in addition to generating a ::marker pseudo-element and enabling the properties described below for that element, causes that element to increment the list item counter list-item. (This does not affect the specified or computed values of the counter properties.)

The list-item counter is a real counter, and can be directly affected using the 'counter-increment' and 'counter-reset' properties. It can also be used in the counter() and counters() function forms.

The CSS3 box module may define other 'display' values which generate a list marker. These should also affect the 'list-item' counter.

Note that this new model makes the marker display type redundant. That display type is therefore obsolete in the CSS3 Lists model.

4. List Content: The 'list-style-type' property

Name: | 'list-style-type'
Value: | <glyph> | <algorithmic> | <numeric> | <alphabetic> | <symbolic> | <non-repeating> | normal | none
Initial: | disc
Applies to: | all elements with 'display: list-item'
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value
Depends on: | none

This property specifies the default appearance of the list item marker if 'list-style-image' has the value 'none' or if the image pointed to by the URI cannot be displayed. The value 'none' specifies no marker, otherwise there are six types of marker: glyphs, algorithmic systems, numeric systems, alphabetic systems, symbolic systems, and non-repeating systems.

Glyphs are single characters, whereas algorithmic, numeric, alphabetic, symbolic and non-repeating systems are designed so that each item in that style gets a deterministicly different marker. This makes lists easier to navigate.

Most numbering systems have a suffix defined. It is used when generating the default content for the marker.

normal
Causes the list-style-type of the counter to be used, as declared by the appropriate @counter rule. In the context of an @counter rule, equivalent to decimal.

Other values are defined in the following sections. User agents should follow these algorithms unless a more normative source is found.

4.1. Glyphs

All markers with the same glyph style should use the same glyph. To obtain other glyphs, authors should use the 'content' property of the ::marker pseudo-element.

<glyph>
box | check | circle | diamond | disc | hyphen | square
box
A hollow square. (like ? U+25A1 WHITE SQUARE, ? U+25FB WHITE MEDIUM SQUARE, or ? U+25FD WHITE MEDIUM SMALL SQUARE)
check
A check mark. On interactive media, it is suggested that the same glyph which is used on the platform to render a checked menu item be used for 'check'. (like ? U+2713 CHECK MARK)
circle
A hollow circle. (like ? U+25E6 WHITE BULLET)
diamond
A filled diamond. On interactive media, it is suggested that the same glyph which is used on the platform next to a selected menu item be used for 'diamond'. On some platforms, this is similar to 'disc'. (like ? U+25C6 BLACK DIAMOND or ? U+2666 BLACK DIAMOND SUIT)
disc
A filled circle. (like . U+2022 BULLET)
hyphen
A hyphen bullet. (like ? U+2043 HYPHEN BULLET or - U+2013 EN DASH)
square
A filled square. (like ? U+25A0 BLACK SQUARE, ? U+25FC BLACK MEDIUM SQUARE, or ? U+25FE BLACK MEDIUM SMALL SQUARE)

The definitions above may be removed and made UA-dependent if it is found that there are discrepancies in the existing implementations.

We could add more values, there are certainly plenty to choose from in UNICODE. How about a star? Or a triangle? Note that the stylesheet of this document uses triangular bullets for notes, and yet that can only be described using a pseudo-element, content property, and unicode escape. Is that too much effort for a simple triangle?

A future level of CSS may provide a way to specify different bullet types at arbitrary nesting levels. The Working Group considered adding an auto value with the following definition, but decided not to include it in this release: "The auto value is intended to cause the UA to use a list numbering style different from that of the nearest ancestor list-item element. The exact rendering depends on the user agent."

Glyphs have no suffix.

4.2. Algorithmic

Algorithmic systems are the most complicated and are described first. For these algorithms, it is assumed that the rendering engine will apply the bidirectionality algorithm after generating the numeric strings.

Note: Readers not accustomed to reading bidirectional text should pay close attention to the directionality of characters versus their associated UNICODE codepoints. All codepoints are given in logical order, but example strings in this document should be rendered in correct reading order.

<algorithmic>
armenian | cjk-ideographic | ethiopic-numeric | georgian | hebrew | japanese-formal | japanese-informal | lower-armenian | lower-roman | simp-chinese-formal | simp-chinese-informal | syriac | tamil | trad-chinese-formal | trad-chinese-informal | upper-armenian | upper-roman
armenian, lower-armenian
This is a simple additive system defined for the range 1 to 99999999. The digits are split into two groups of four (if there are less than eight digits, the least significant group is filled first). Within each group, appropriate digits are picked from the following list (at most one per column) and written in descending order by value (thousands first). Any characters in the most significant group are then combined with a circumflex accent, ?^ U+0302.
Lower-armenian numbering system
Thousands | Hundreds | Tens | Units
Values | Codepoints | Values | Codepoints | Values | Codepoints | Values | Codepoints
1000 ? U+057C 100 ? U+0573 10 ? U+056A 1 ? U+0561
2000 ? U+057D 200 ? U+0574 20 ? U+056B 2 ? U+0562
3000 ? U+057E 300 ? U+0575 30 ? U+056C 3 ? U+0563
4000 ? U+057F 400 ? U+0576 40 ? U+056D 4 ? U+0564
5000 ? U+0580 500 ? U+0577 50 ? U+056E 5 ? U+0565
6000 ? U+0581 600 ? U+0578 60 ? U+056F 6 ? U+0566
7000 ?? U+0578 U+0582 700 ? U+0579 70 ? U+0570 7 ? U+0567
8000 ? U+0583 800 ? U+057A 80 ? U+0571 8 ? U+0568
9000 ? U+0584 900 ? U+057B 90 ? U+0572 9 ? U+0569

The two characters for the 7000 digit should be combined and rendered as one character. When the U+0302 character combines with the 7000 characters, it does so as if the two characters were one.

The suffix for the armenian numbering system is a dot . U+002E.

Numbers outside the range of the armenian system are rendered using the decimal numbering style.

Decimal 7482951 in lower-armenian is ??^?^?^???? U+0578 U+0582 U+0302 U+0576 U+0302 U+0571 U+0302 U+057D U+057B U+056E U+0561.

cjk-ideographic
The cjk-ideographic algorithm is used by several numbering systems, using different sets of digits. These systems are defined for numbers greater than or equal to 0 and less than 1016. Numbers less than zero or equal to or greater than 1016 should use the decimal system. The core algorithm is as follows:
  1. Split the decimal number into groups of four digits, starting with the least significant digit.
  2. Ignoring groups that have the value zero, append the second group marker to the second group, the third group marker to the third group, and the fourth group marker to the fourth group. These markers are defined in the tables for the specific numbering systems. The first group has no marker.
  3. For each group, ignoring digits that have the value zero, append the second digit marker to the second digit, the third digit marker to the third digit, and the fourth digit marker to the fourth digit. These markers are defined in the tables for the specific numbering systems. The first digit has no marker.
  4. For any group with a value less than 20, remove the second digit (the 1 in the tens column). Leave any associated markers.
  5. Concatenate the groups back into a single string, least significant group last.
  6. Collapse any consecutive runs of 0 digits to a single 0.
  7. Replace each digit with the relevant character selected from the numbering system's table.

The suffix for the cjk-ideographic numbering systems is a dot . U+002E. Is there a better suffix to use?

If specified explicitly, the cjk-ideograph keyword should be handled like trad-chinese-informal.

ethiopic-numeric
The following algorithm converts decimal digits to ethiopic numbers.
  1. Split the number into groups of two digits, starting with the least significant decimal digit.
  2. Number each group sequentially, starting from the least significant as group number zero.
  3. If the group has an odd number (as given in the previous step) and has the value 1, or if the group is the most significant one and has the value 1, or if the group has the value zero, then remove the digit (but leave the group, so it still has a separator appended below).
  4. For each remaining digit, substitute the relevant ethiopic character from the list below.
    Ethiopic numbering system
    Tens | Units
    Values | Codepoints | Values | Codepoints
    10 ? U+1372 1 ? U+1369
    20 ? U+1373 2 ? U+136A
    30 ? U+1374 3 ? U+136B
    40 ? U+1375 4 ? U+136C
    50 ? U+1376 5 ? U+136D
    60 ? U+1377 6 ? U+136E
    70 ? U+1378 7 ? U+136F
    80 ? U+1379 8 ? U+1370
    90 ? U+137A 9 ? U+1371
  5. For each group with an odd number (as given in the second step), append &#x137B U+137B.
  6. For each group with an even number (as given in the second step), except the group with number 0, append &#x137C U+137C.
  7. Concatenate the groups into one string.

This system is defined for all numbers greater than zero. For zero and negative numbers, the decimal system is used instead.

The suffix for the ethiopic-numeric numbering systems is a dot . U+002E. Is there a better suffix to use? The alphabetic ethiopic systems use a different suffix.

The decimal number 100, in ethiopic, is ? U+137B

The decimal number 78010092, in ethiopic, is ???????? U+1378 U+1370 U+137B U+1369 U+137C U+137B U+137A U+136A.

The decimal number 780000001092, in ethiopic, is ?????????? U+1378 U+1370 U+137B U+1369 U+137C U+137B U+137C U+137B U+137A U+136A.

georgian
This is a simple additive system (like armenian) defined only for the range 1 to 19999. The appropriate digits are picked from the following list (at most one per column) and written in descending order by value (tens of thousands first).
Georgian numbering system
Tens of Thousands | Thousands | Hundreds | Tens | Units
Values | Codepoints | Values | Codepoints | Values | Codepoints | Values | Codepoints | Values | Codepoints
10000 ? U+10EF 1000 ? U+10E8 100 ? U+10E0 10 ? U+10D8 1 ? U+10D0
2000 ? U+10E9 200 ? U+10E1 20 ? U+10D9 2 ? U+10D1
3000 ? U+10EA 300 ? U+10E2 30 ? U+10DA 3 ? U+10D2
4000 ? U+10EB 400 ? U+10E3 40 ? U+10DB 4 ? U+10D3
5000 ? U+10EC 500 ? U+10F3 50 ? U+10DC 5 ? U+10D4
6000 ? U+10ED 600 ? U+10E4 60 ? U+10F2 6 ? U+10D5
7000 ? U+10EE 700 ? U+10E5 70 ? U+10DD 7 ? U+10D6
8000 ? U+10F4 800 ? U+10E6 80 ? U+10DE 8 ? U+10F1
9000 ? U+10F5 900 ? U+10E7 90 ? U+10DF 9 ? U+10D7

Note that these codepoints are not all sequential.

The suffix for the georgian numbering system is a dot . U+002E.

Numbers outside the range of the georgian system are rendered using the decimal numbering style.

hebrew
Due to the complexities of the hebrew system, an exact algorithm is not given here, only a description of the rules that implementations should respect. The hebrew system is based on addition and is only defined for positive numbers and zero. If someone can come up with a correct exact algorithm, then I would be happy to include it. Note: These rules have an error. I am waiting to get confirmation of how to fix them.

For each group of three digits in the decimal system, the requisite numbers are selected from the following list.

Hebrew numbering system
Hundreds | Tens | Units
Values | Codepoints | Values | Codepoints | Values | Codepoints
100 ? U+05E7 10 ? U+05D9 1 ? U+05D0
200 ? U+05E8 20 ? U+05DB 2 ? U+05D1
300 ? U+05E9 30 ? U+05DC 3 ? U+05D2
400 ? U+05EA 40 ? U+05DE 4 ? U+05D3
500 ?? U+05EA U+05E7 50 ? U+05E0 5 ? U+05D4
600 ?? U+05EA U+05E8 60 ? U+05E1 6 ? U+05D5
700 ?? U+05EA U+05E9 70 ? U+05E2 7 ? U+05D6
800 ?? U+05EA U+05EA 80 ? U+05E4 8 ? U+05D7
900 ??? U+05EA U+05EA U+05E7 90 ? U+05E6 9 ? U+05D8

Groups for more significant numbers are placed before groups for less significant numbers (as in the decimal system). Each group is separated by a space U+0020.

If the last two digits of a group (when represented in decimal) are 15 or 16, they should be expressed not as ?? U+05D9 U+05D4 (10+5) and ?? U+05D9 U+05D5 (10+6), but as ?? U+05D8 U+05D5 (9+6) and ?? U+05D8 U+05D6 (9+7). This is done to avoid a close resemblance to the Tetragrammaton (four-letter name of God) ???? U+05D9 U+05D4 U+05D5 U+05D4. Although this convention is originally derived from religious practice, it is universally used even in completely secular contexts.

The numerical value of each letter is fixed and not determined by position, so reordering a number group will not change its value. This may be done when a number spells out a word with negative connotations. For instance, 298, ??? U+05E8 U+05E6 U+05D7 (200+90+8), is the Hebrew for "murder", so it is sometimes written as ??? U+05E8 U+05D7 U+05E6 (200+8+90). Words are sometimes similarly rearranged when a reordered form has especially positive connotations, for example 18, ?? U+05D9 U+05D7 (10+8) is often written as ?? U+05D7 U+05D9 (8+10), the Hebrew for "alive". Unlike the exception for 15 and 16, using the regular form in these cases is not considered an error.

When a group or set of adjacent groups would have the numerical value zero, the word for "thousands", ???? U+05D0 U+05DC U+05E4 U+05D9, is repeatedly inserted, one for each group up to the zero. The final group of thousands in a chain has a final form ? U+05DD appended at the end. For instance the decimal number 3000123 would be represented as ? ???? ????? ??? U+05D2 U+0020 U+05D0 U+05DC U+05E4 U+05D9 U+0020 U+05D0 U+05DC U+05E4 U+05D9 U+05DD U+0020 U+05E7 U+05DB U+05D2 (3, space, thousands, space, thousands with final form, space, 100+20+3). For grammatical reasons, the first "thousands" word after a group consisting of only the number 1 is represented by ??? U+05D0 U+05DC U+05E3. It does not have the final ? U+05DD appended, even if it occurs on its own. The number 2000 at the end of the number is represented by ?????? U+05D0 U+05DC U+05E4 U+05D9 U+05D9 U+05DD (and does not get anything else appended at the end). The number 2 is not otherwise special (for example 2000000 is simply ? ???? ????? U+05D1 U+0020 U+05D0 U+05DC U+05E4 U+05D9 U+0020 U+05D0 U+05DC U+05E4 U+05D9 U+05DD (2, space, thousands, space, thousands with final form).

Some text about geresh/gershayim is commented out here.

For zero, the word ??? U+05D0 U+05E4 U+05E1 is used.

The suffix for the hebrew numbering system is a dot . U+002E.

For numbers less than zero, the 'decimal' system is used instead.

This table shows the decimal number in the first cell, and the equivalent hebrew number in the second.

Decimal | Hebrew
-3 | -3
-2 | -2
-1 | -1
0 ???
1 ?
2 ?
3 ?
4 ?
5 ?
97 ??
98 ??
99 ??
100 ?
101 ??
944 ?????
945 ?????
946 ?????
999 ?????
1000 ???
1001 ? ?
1998 ? ?????
1999 ? ?????
2000 ??????
2001 ? ?
2003 ? ?
2748 ? ????
2750 ? ???
1000000 ??? ?????
1500000 ? ?? ?????
2000000 ? ???? ?????
9999999 ? ????? ?????
10000212 ? ???? ????? ???
10000425 ? ???? ????? ???
10000851 ? ???? ????? ????
10001064 ? ? ??
10001277 ? ? ???
980000002000 ???? ???? ???? ????? ??????
990000002000 ???? ???? ???? ????? ??????
1000000000000 ??? ???? ???? ?????
1000500000000 ??? ???? ???? ????? ?? ???? ?????
1000500002000 ??? ???? ???? ????? ?? ??????
1003000000000 ? ? ???? ???? ?????
1047500002000 ? ?? ?? ??????
4823885215073 ? ???? ???? ??? ??
5249872460970 ? ??? ???? ?? ????

This example (like all other examples) is non-normative. If one of the numbers above is inconsistent with the rules described above, then the example should be disregarded.

japanese-formal
This uses the cjk-ideographic system with the following table.
Formal Japanese numbering system
Values Codepoints
Second Group Marker ? U+4E07
Third Group Marker ? U+5104
Fourth Group Marker ? U+5146
Second Digit Marker ? U+62FE
Third Digit Marker ? U+4F70
Fourth Digit Marker ? U+4EDF
Digit 0 ? U+96F6
Digit 1 ? U+58F9
Digit 2 ? U+8CB3
Digit 3 ? U+53C3
Digit 4 ? U+8086
Digit 5 ? U+4F0D
Digit 6 ? U+9678
Digit 7 ? U+67D2
Digit 8 ? U+634C
Digit 9 ? U+7396
japanese-informal
This uses the cjk-ideographic system with the following table.
Informal Japanese numbering system
Values Codepoints
Second Group Marker ? U+842C
Third Group Marker ? U+5104
Fourth Group Marker ? U+5146
Second Digit Marker ? U+842C
Third Digit Marker ? U+5104
Fourth Digit Marker ? U+5146
Digit 0 ? U+96F6
Digit 1 ? U+58F9
Digit 2 ? U+8D30
Digit 3 ? U+53C1
Digit 4 ? U+8086
Digit 5 ? U+4F0D
Digit 6 ? U+9646
Digit 7 ? U+67D2
Digit 8 ? U+634C
Digit 9 ? U+7396
lower-roman
The algorithm for this numbering style is identical to the upper-roman style but using ?-? U+2170-U+217F instead of ?-? U+2160-U+216F, and ignoring step 2 (i.e. not treating numbers 1000-40000 in a special way, since there are no lowercase equivalents to ? U+2181 and ? U+2182).
simp-chinese-formal
This uses the cjk-ideographic system with the following table.
Formal simple Chinese numbering system
Values Codepoints
Second Group Marker ? U+4E07
Third Group Marker ? U+5104
Fourth Group Marker ? U+5146
Second Digit Marker ? U+4E07
Third Digit Marker ? U+4EBF
Fourth Digit Marker ? U+5146
Digit 0 ? U+96F6
Digit 1 ? U+58F9
Digit 2 ? U+8CB3
Digit 3 ? U+53C3
Digit 4 ? U+8086
Digit 5 ? U+4F0D
Digit 6 ? U+9678
Digit 7 ? U+67D2
Digit 8 ? U+634C
Digit 9 ? U+7396
simp-chinese-informal
This uses the cjk-ideographic system with the following table.
Informal simple Chinese numbering system
Values Codepoints
Second Group Marker ? U+842C
Third Group Marker ? U+5104
Fourth Group Marker ? U+5146
Second Digit Marker ? U+842C
Third Digit Marker ? U+5104
Fourth Digit Marker ? U+5146
Digit 0 ? U+96F6
Digit 1 ? U+58F9
Digit 2 ? U+8CB3
Digit 3 ? U+53C3
Digit 4 ? U+8086
Digit 5 ? U+4F0D
Digit 6 ? U+9678
Digit 7 ? U+67D2
Digit 8 ? U+634C
Digit 9 ? U+7396
syriac
The Syriac number system is capable of representing numbers greater than 0 and less than 1010. The following algorithm should be used to convert a number to the syriac system:
  1. Divide the original number by 10000000.
  2. If the resulting number has a non-zero hundreds digit, add to the string the following characters, according to the value of the hundreds digit:
    Value Codepoints
    1 ?? U+0729 U+032D
    2 ?? U+072A U+032D
    3 ?? U+072B U+032D
    4 ?? U+072C U+032D
    5 ???? U+072C U+032D U+072A U+032D
    6 ???? U+072C U+032D U+0729 U+032D
    7 ???? U+072C U+032D U+072B U+032D
    8 ???? U+072C U+032D U+072C U+032D
    9 ?????? U+072C U+032D U+072C U+032D U+0729 U+032D
  3. If the resulting number has a non-zero tens digit, add to the string the following characters, according to the value of the tens digit:
    Value Codepoints
    1 ?? U+071D U+032D
    2 ?? U+071F U+032D
    3 ?? U+0720 U+032D
    4 ?? U+0721 U+032D
    5 ?? U+0722 U+032D
    6 ?? U+0723 U+032D
    7 ?? U+0726 U+032D
    8 ?? U+0726 U+032D
    9 ?? U+0728 U+032D
  4. If the resulting number has a non-zero ones digit, add to the string the following characters, according to the value of the ones digit:
    Value Codepoints
    1 ?? U+0710 U+032D
    2 ?? U+0712 U+032D
    3 ?? U+0723 U+032D
    4 ?? U+0715 U+032D
    5 ?? U+0717 U+032D
    6 ?? U+0718 U+032D
    7 ?? U+0719 U+032D
    8 ?? U+071A U+032D
    9 ?? U+071B U+032D
  5. Divide the original number by 10,000. Follow steps 2 to 4, replacing the character ?? U+032D with ?_ U+0331.
  6. Divide the original number by 1,000. Follow step 4, replacing the character ?? U+032D with ?? U+0301.
  7. Apply steps 2 and 3 to the original number, omitting the ?? U+032D character.
  8. If the ones digit of the original number is zero, and the only character in the string (including combining characters) is ? U+071F, ? U+0721, or ? U+0722, add another instance of that character to the string. Otherwise, if the ones digit of the original number is not zero, apply step 4 to the original number, omitting the ?? U+032D character.

This assumes that numbers 10000 to 999999 are represented using the combination of characters with the combining macron below. It is possible to represent them using the combination of characters with the combining acute accent, as well. Which form is preferred in practice?

The suffix for the syriac numbering system is a dot . U+002E.

Numbers outside the range of the syriac system are rendered using the decimal numbering style.

tamil
This system is defined for numbers in the range of 1 to 9999 inclusive, for numbers outside this range, the decimal system should be used instead. Tamil uses a combination of multiplication and addition, using the following algorithm:
  1. Insert ? U+0BF2 between the fourth digit and the third digit if there is a fourth digit, counting from the least significant digit. (If the number is greater than 999.)
  2. Insert ? U+0BF1 between the third digit and the second digit if there is a third digit, counting from the least significant digit. (If the number is greater than 99.)
  3. Insert ? U+0BF0 between the second digit and the first digit if there is a second digit, counting from the least significant digit. (If the number is greater than 9.)
  4. Each decimal digit is substituted for a tamil digit using the table below. Occurances of the decimal 0 character are dropped.
    Tamil numbering system
    Values Codepoints
    1 ? U0BE79
    2 ? U+0BE8
    3 ? U+0BE9
    4 ? U+0BEA
    5 ? U+0BEB
    6 ? U+0BEC
    7 ? U+0BED
    8 ? U+0BEE
    9 ? U+0BEF

The suffix for the tamil numbering system is a dot . U+002E.

Numbers outside the range of the tamil system are rendered using the decimal numbering style.

The number 420, in tamil, is written ???&#x0BF0 U+0BEA U+0BF1 U+0BE8 U+0BF0.

trad-chinese-formal
This uses the cjk-ideographic system with the following table.
Formal Traditional Chinese numbering system
Values Codepoints
Second Group Marker ? U+4E07
Third Group Marker ? U+4EBF
Fourth Group Marker ? U+5146
Second Digit Marker ? U+4E07
Third Digit Marker ? U+4EBF
Fourth Digit Marker ? U+5146
Digit 0 ? U+96F6
Digit 1 ? U+4E00
Digit 2 ? U+4EBC
Digit 3 ? U+4E09
Digit 4 ? U+56DB
Digit 5 ? U+4E94
Digit 6 ? U+516D
Digit 7 ? U+4E03
Digit 8 ? U+516B
Digit 9 ? U+4E5D
trad-chinese-informal
This uses the cjk-ideographic system with the following table.
Informal traditional Chinese numbering system
Values Codepoints
Second Group Marker ? U+842C
Third Group Marker ? U+5104
Fourth Group Marker ? U+5146
Second Digit Marker ? U+842C
Third Digit Marker ? U+5104
Fourth Digit Marker ? U+5146
Digit 0 ? U+96F6
Digit 1 ? U+4E00
Digit 2 ? U+4EBC
Digit 3 ? U+4E09
Digit 4 ? U+56DB
Digit 5 ? U+4E94
Digit 6 ? U+516D
Digit 7 ? U+4E03
Digit 8 ? U+516B
Digit 9 ? U+4E5D
upper-armenian
This system is identical to the lower-armenian system but uses the following codepoints instead.
Upper-armenian numbering system
Thousands | Hundreds | Tens | Units
Values | Codepoints | Values | Codepoints | Values | Codepoints | Values | Codepoints
1000 ? U+054C 100 ? U+0543 10 ? U+053A 1 ? U+0531
2000 ? U+054D 200 ? U+0544 20 ? U+053B 2 ? U+0532
3000 ? U+054E 300 ? U+0545 30 ? U+053C 3 ? U+0533
4000 ? U+054F 400 ? U+0546 40 ? U+053D 4 ? U+0534
5000 ? U+0550 500 ? U+0547 50 ? U+053E 5 ? U+0535
6000 ? U+0551 600 ? U+0548 60 ? U+053F 6 ? U+0536
7000 ?? U+0548 U+0552 700 ? U+0549 70 ? U+0540 7 ? U+0537
8000 ? U+0553 800 ? U+054A 80 ? U+0541 8 ? U+0538
9000 ? U+0554 900 ? U+054B 90 ? U+0542 9 ? U+0539

There are two letters for 10,000 and 20,000 (U+0555 and U+0556 respectively), but whether and how they should be used is unclear.

Decimal 7482951 in upper-armenian is ??^?^?^???? U+0548 U+0552 U+0302 U+0546 U+0302 U+0541 U+0302 U+054D U+054B U+053E U+0531.

upper-roman
Numbers are converted to roman numerals using the steps described below. The phrase "take the three least significant numbers" means divide by 1000, truncate (drop the fractional part), multiply by one thousand, and subtract this from the original number. So the three least significant figures of 1004 is 4.
  1. If the number is in the range 0 to 1000 inclusive, use the following steps:
    1. If the number is 1000, add ? U+216F and skip to the end.
    2. If the number is 900 or more, add ?? U+216D U+216F and subtract 900.
    3. If the number is 500 or more, add ? U+216E and subtract 500.
    4. If the number is 400 or more, add ?? U+216D U+216E and subtract 400.
    5. While the number is greater than or equal to 100, add ? U+216D and subtract 100.
    6. If the number is 90 or more, add ?? U+2169 U+216D and subtract 90.
    7. If the number is 50 or more, add ? U+216C and subtract 50.
    8. If the number is 40 or more, add ?? U+2169 U+216C and subtract 40.
    9. While the number is greater than 12, add ? U+2169 and subtract 10.
    10. If the number is greater than 0, then add the appropriate roman numeral from ? U+2160 (1) to ? U+216B (12). For example, if the number is 8, add ? U+2167.
  2. If the number is in the range 1000 to 40000 exclusive, then take the three least significant numbers and convert them using step 1. Then convert the remainder using the following steps and prepend it to the result.
    1. While the number is greater than or equal to 10000, add ? U+2182 and subtract 10000.
    2. If the number is 9000, add ?? U+216F U+2182 and skip to the end.
    3. If the number is 4000, add ?? U+216F U+2181 and skip to the end.
    4. If the number is 5000 or more, add ? U+2181 and subtract 5000.
    5. While the number is greater than 0, add ? U+216F and subtract 1000.
  3. If the number is greater than 40000, then take the three least significant figures and convert them using step 1, calling that the result. Then convert the remainder by dividing it by 1000, passing it through the entire algorithm starting at the top, adding an overbar to it, and prepending it to the current result. For very large numbers, this step may be entered several times, resulting in the first few characters of the result having multiple overbars.

The suffix for roman numerals is a dot . U+002E.

Zero and negative numbers are rendered using the decimal numbering style.

For example, decimal 4294967296 is, in the upper-roman numbering style:

triple overbar ?, double overbar ? ? ? ? ?, overbar ? ? ? ? ?, no overbar ? ? ? ? ?

Similarly, decimal 15000 is ?? (U+2182 U+2181) and decimal -47 would be rendered as -47 (negative numbers do not have roman numeral equivalents).

4.3. Numeric

Numeric and alphabetic systems use a simple repeating scheme. Each digit is used in turn, and when the digits are exhausted, an extra column of digits is added in front and all the combinations used up to that point are reused for each of the digits. For example, if the digits are A, B and C, then the sequence would be A, B, C, AA, AB, AC, BA, BB, BC, CA, CB, CC, AAA, AAB, AAC, ABA, ABB, etc.

The difference between numeric and alphabetic systems is that numeric systems have a zero value which is not a significant digit (1, 2, ... 9, 10, 11 ...), while alphabetic systems have no zero value and their first digit is significant (A, B, ... Z, AA, AB ...). (An insignificant digit is one which could be prefixed without changing the meaning of the number. For example, 1 and 0001 are both representations of the number one, while A and AAAA represent values 18278 positions apart.) Consequently, numeric systems may go zero or negative, while alphabetic systems are only defined for positive values. If an alphabetic system is selected to render zero or a negative number then the decimal numbering style must be used instead.

<numeric>
arabic-indic | binary | bengali | cambodian | decimal | decimal-leading-zero | devanagari | gujarati | gurmukhi | kannada | khmer | lao | lower-hexadecimal | malayalam | mongolian | myanmar | octal | oriya | persian | telugu | tibetan | thai | upper-hexadecimal | urdu

Numeric systems are detailed in the table below. The value for "one" is always the second character listed, the first character being the "zero" value.

For all these systems, negative numbers are first converted as if they were positive numbers, then have - U+002D prefixed.

Numeric repeating systems
System | Characters | Codepoints | Base | Suffix | Notes
arabic-indic | ? ? ? ? ? ? ? ? ? ? | U+0660, U+0661, U+0662, U+0663, U+0664, U+0665, U+0666, U+0667, U+0668, U+0669 | 10 | . U+002E |
binary | 0 1 | U+0030, U+0031 | 2 | . U+002E |
bengali | ? ? ? ? ? ? ? ? ? ? | U+09E6, U+09E7, U+09E8, U+09E9, U+09EA, U+09EB, U+09EC, U+09ED, U+09EE, U+09EF | 10 | . U+002E |
cambodian, khmer | ? ? ? ? ? ? ? ? ? ? | U+17E0, U+17E1, U+17E2, U+17E3, U+17E4, U+17E5, U+17E6, U+17E7, U+17E8, U+17E9 | 10 | . U+002E |
decimal | 0 1 2 3 4 5 6 7 8 9 | U+0030, U+0031, U+0032, U+0033, U+0034, U+0035, U+0036, U+0037, U+0038, U+0039 | 10 | . U+002E |
decimal-leading-zero | 0 1 2 3 4 5 6 7 8 9 | U+0030, U+0031, U+0032, U+0033, U+0034, U+0035, U+0036, U+0037, U+0038, U+0039 | 10 | . U+002E | Note 1
devanagari | ? ? ? ? ? ? ? ? ? ? | U+0966, U+0967, U+0968, U+0969, U+096A, U+096B, U+096C, U+096D, U+096E, U+096F | 10 | . U+002E |
gujarati | ? ? ? ? ? ? ? ? ? ? | U+0AE6, U+0AE7, U+0AE8, U+0AE9, U+0AEA, U+0AEB, U+0AEC, U+0AED, U+0AEE, U+0AEF | 10 | . U+002E |
gurmukhi | ? ? ? ? ? ? ? ? ? ? | U+0A66, U+0A67, U+0A68, U+0A69, U+0A6A, U+0A6B, U+0A6C, U+0A6D, U+0A6E, U+0A6F | 10 | . U+002E |
kannada | ? ? ? ? ? ? ? ? ? ? | U+0CE6, U+0CE7, U+0CE8, U+0CE9, U+0CEA, U+0CEB, U+0CEC, U+0CED, U+0CEE, U+0CEF | 10 | . U+002E |
lower-hexadecimal | 0 1 2 3 4 5 6 7 8 9 a b c d e f | U+0030, U+0031, U+0032, U+0033, U+0034, U+0035, U+0036, U+0037, U+0038, U+0039, U+0061, U+0062, U+0063, U+0064, U+0065, U+0066 | 16 | . U+002E |
lao | ? ? ? ? ? ? ? ? ? ? | U+0ED0, U+0ED1, U+0ED2, U+0ED3, U+0ED4, U+0ED5, U+0ED6, U+0ED7, U+0ED8, U+0ED9 | 10 | . U+002E |
malayalam | ? ? ? ? ? ? ? ? ? ? | U+0D66, U+0D67, U+0D68, U+0D69, U+0D6A, U+0D6B, U+0D6C, U+0D6D, U+0D6E, U+0D6F | 10 | . U+002E |
mongolian | ? ? ? ? ? ? ? ? ? ? | U+1810, U+1811, U+1812, U+1813, U+1814, U+1815, U+1816, U+1817, U+1818, U+1819 | 10 | . U+002E |
myanmar | ? ? ? ? ? ? ? ? ? ? | U+1040, U+1041, U+1042, U+1043, U+1044, U+1045, U+1046, U+1047, U+1048, U+1049 | 10 | . U+002E |
octal | 0 1 2 3 4 5 6 7 | U+0030, U+0031, U+0032, U+0033, U+0034, U+0035, U+0036, U+0037 | 8 | . U+002E |
oriya | ? ? ? ? ? ? ? ? ? ? | U+0B66, U+0B67, U+0B68, U+0B69, U+0B6A, U+0B6B, U+0B6C, U+0B6D, U+0B6E, U+0B6F | 10 | . U+002E |
persian, urdu | ? ? ? ? ? ? ? ? ? ? | U+06F0, U+06F1, U+06F2, U+06F3, U+06F4, U+06F5, U+06F6, U+06F7, U+06F8, U+06F9 | 10 | . U+002E |
telugu | ? ? ? ? ? ? ? ? ? ? | U+0C66, U+0C67, U+0C68, U+0C69, U+0C6A, U+0C6B, U+0C6C, U+0C6D, U+0C6E, U+0C6F | 10 | . U+002E |
tibetan | ? ? ? ? ? ? ? ? ? ? | U+0F20, U+0F21, U+0F22, U+0F23, U+0F24, U+0F25, U+0F26, U+0F27, U+0F28, U+0F29 | 10 | . U+002E |
thai | ? ? ? ? ? ? ? ? ? ? | U+0E50, U+0E51, U+0E52, U+0E53, U+0E54, U+0E55, U+0E56, U+0E57, U+0E58, U+0E59 | 10 | . U+002E |
upper-hexadecimal | 0 1 2 3 4 5 6 7 8 9 A B C D E F | U+0030, U+0031, U+0032, U+0033, U+0034, U+0035, U+0036, U+0037, U+0038, U+0039, U+0041, U+0042, U+0043, U+0044, U+0045, U+0046 | 16 | . U+002E |

Note 1: Numbers -9 to 9 in the decimal-leading-zero system should be prefixed by an extra single 0 U+0030.

The decimal number -7645, in the thai numbering system, is -???? U+002D U+0E57 U+0E56 U+0E54 U+0E55.

4.4. Alphabetic

<alphabetic>
afar | amharic | amharic-abegede | cjk-earthly-branch | cjk-heavenly-stem | ethiopic | ethiopic-abegede | ethiopic-abegede-am-et | ethiopic-abegede-gez | ethiopic-abegede-ti-er | ethiopic-abegede-ti-et | ethiopic-halehame-aa-er | ethiopic-halehame-aa-et | ethiopic-halehame-am-et | ethiopic-halehame-gez | ethiopic-halehame-om-et | ethiopic-halehame-sid-et | ethiopic-halehame-so-et | ethiopic-halehame-ti-er | ethiopic-halehame-ti-et | ethiopic-halehame-tig | hangul | hangul-consonant | hiragana | hiragana-iroha | katakana | katakana-iroha | lower-alpha | lower-greek | lower-norwegian | lower-latin | oromo | sidama | somali | tigre | tigrinya-er | tigrinya-er-abegede | tigrinya-et | tigrinya-et-abegede | upper-alpha | upper-greek | upper-norwegian | upper-latin

Alphabetic systems are detailed in the next table. They are similar to numeric systems, see the previous section for more details. The value for "one" is always the first character listed, there being no "zero" value for these systems. Note: Many of the codepoints in the following table are not contiguous, and several systems in this table use a suffix other than a dot.

Alphabetic repeating systems
System | Characters | Codepoints | Base | Suffix | Notes
afar, ethiopic-halehame-aa-et, ethiopic-halehame-aa-er | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+1200, U+1208, U+1210, U+1218, U+1228, U+1230, U+1260, U+1270, U+1290, U+12A0, U+12A8, U+12C8, U+12D0, U+12E8, U+12F0, U+1308, U+1338, U+1348 | 18 | ? U+1366 |
amharic, ethiopic-halehame-am-et | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+1200, U+1208, U+1210, U+1218, U+1220, U+1228, U+1230, U+1238, U+1240, U+1260, U+1270, U+1278, U+1280, U+1290, U+1298, U+12A0, U+12A8, U+12B8, U+12C8, U+12D0, U+12D8, U+12E0, U+12E8, U+12F0, U+1300, U+1308, U+1320, U+1328, U+1330, U+1338, U+1340, U+1348, U+1350 | 33 | ? U+1366 |
amharic-abegede, ethiopic-abegede-am-et | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+12A0, U+1260, U+1308, U+12F0, U+1300, U+1200, U+12C8, U+12D8, U+12E0, U+1210, U+1320, U+1328, U+12E8, U+12A8, U+12B8, U+1208, U+1218, U+1290, U+1298, U+1220, U+12D0, U+1348, U+1338, U+1240, U+1228, U+1230, U+1238, U+1270, U+1278, U+1280, U+1340, U+1330, U+1350 | 33 | ? U+1366 |
cjk-earthly-branch | ? ? ? ? ? ? ? ?? ? ? ? | U+5B50, U+4E11, U+5BC5, U+536F, U+8FB0, U+5DF3, U+5348, U+672A, U+7533, U+9149, U+620C, U+4EA5 | 12 | . U+002E |
cjk-heavenly-stem | ? ? ? ? ? ? ? ?? ? | U+7532, U+4E59, U+4E19, U+4E01, U+620A, U+5DF1, U+5E9A, U+8F9B, U+58EC, U+7678 | 10 | . U+002E |
ethiopic, ethiopic-halehame-gez | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+1200, U+1208, U+1210, U+1218, U+1220, U+1228, U+1230, U+1240, U+1260, U+1270, U+1280, U+1290, U+12A0, U+12A8, U+12C8, U+12D0, U+12D8, U+12E8, U+12F0, U+1308, U+1320, U+1330, U+1338, U+1340, U+1348, U+1350 | 26 | ? U+1366 |
ethiopic-abegede, ethiopic-abegede-gez | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+12A0, U+1260, U+1308, U+12F0, U+1200, U+12C8, U+12D8, U+1210, U+1320, U+12E8, U+12A8, U+1208, U+1218, U+1290, U+1220, U+12D0, U+1348, U+1338, U+1240, U+1228, U+1230, U+1270, U+1280, U+1340, U+1330, U+1350 | 26 | ? U+1366 |
hangul-consonant | ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+3131, U+3134, U+3137, U+3139, U+3141, U+3142, U+3145, U+3147, U+3148, U+314A, U+314B, U+314C, U+314D, U+314E | 14 | . U+002E |
hangul | ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+AC00, U+B098, U+B2E4, U+B77C, U+B9C8, U+BC14, U+C0AC, U+C544, U+C790, U+CC28, U+CE74, U+D0C0, U+D30C, U+D558 | 14 | . U+002E |
hiragana-iroha | ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ?? ? ? ? ? ? ? ?? ? ? ? ? ? ? ?? ? ? ? ? ? ? ?? ? ? ? ? ? ? | U+3044, U+308D, U+306F, U+306B, U+307B, U+3078, U+3068, U+3061, U+308A, U+306C, U+308B, U+3092, U+308F, U+304B, U+3088, U+305F, U+308C, U+305D, U+3064, U+306D, U+306A, U+3089, U+3080, U+3046, U+3090, U+306E, U+304A, U+304F, U+3084, U+307E, U+3051, U+3075, U+3053, U+3048, U+3066, U+3042, U+3055, U+304D, U+3086, U+3081, U+307F, U+3057, U+3091, U+3072, U+3082, U+305B, U+3059 | 47 | . U+002E | One character is not in this list.
hiragana | ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ?? ? ? ? ? ? ? ?? ? ? ? ? ? ? ?? ? ? ? ? ? ? ?? ? ? ? ? ? ? ? | U+3042, U+3044, U+3046, U+3048, U+304A, U+304B, U+304D, U+304F, U+3051, U+3053, U+3055, U+3057, U+3059, U+305B, U+305D, U+305F, U+3061, U+3064, U+3066, U+3068, U+306A, U+306B, U+306C, U+306D, U+306E, U+306F, U+3072, U+3075, U+3078, U+307B, U+307E, U+307F, U+3080, U+3081, U+3082, U+3084, U+3086, U+3088, U+3089, U+308A, U+308B, U+308C, U+308D, U+308F, U+3090, U+3091, U+3092, U+3093 | 48 | . U+002E | One character is not in this list.
katakana-iroha | ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ?? ? ? ? ? ? ? ?? ? ? ? ? ? ? ?? ? ? ? ? ? ? ?? ? ? ? ? ? ? | U+30A4, U+30ED, U+30CF, U+30CB, U+30DB, U+30D8, U+30C8, U+30C1, U+30EA, U+30CC, U+30EB, U+30F2, U+30EF, U+30AB, U+30E8, U+30BF, U+30EC, U+30BD, U+30C4, U+30CD, U+30CA, U+30E9, U+30E0, U+30A6, U+30F0, U+30CE, U+30AA, U+30AF, U+30E4, U+30DE, U+30B1, U+30D5, U+30B3, U+30A8, U+30C6, U+30A2, U+30B5, U+30AD, U+30E6, U+30E1, U+30DF, U+30B7, U+30F1, U+30D2, U+30E2, U+30BB, U+30B9 | 47 | . U+002E | One character is not in this list.
katakana | ? ? ? ? ? ? ? ? &#x30B1, ? ? ? ? ? ? ?? &#x30C4, ? ? ? ? ? ?? ? &#x30D2, ? ? ? ? ?? ? ? &#x30E4, ? ? ? ?? ? ? ? &#x30F0, ? ? ? | U+30A2, U+30A4, U+30A6, U+30A8, U+30AA, U+30AB, U+30AD, U+30AF, U+30B1, U+30B3, U+30B5, U+30B7, U+30B9, U+30BB, U+30BD, U+30BF, U+30C1, U+30C4, U+30C6, U+30C8, U+30CA, U+30CB, U+30CC, U+30CD, U+30CE, U+30CF, U+30D2, U+30D5, U+30D8, U+30DB, U+30DE, U+30DF, U+30E0, U+30E1, U+30E2, U+30E4, U+30E6, U+30E8, U+30E9, U+30EA, U+30EB, U+30EC, U+30ED, U+30EF, U+30F0, U+30F1, U+30F2, U+30F3 | 48 | . U+002E | Four characters are not in this list.
lower-alpha, lower-latin | a b c d e f g h i j k l m n o p q r s t u v w x y z | U+0061, U+0062, U+0063, U+0064, U+0065, U+0066, U+0067, U+0068, U+0069, U+006A, U+006B, U+006C, U+006D, U+006E, U+006F, U+0070, U+0071, U+0072, U+0073, U+0074, U+0075, U+0076, U+0077, U+0078, U+0079, U+007A | 26 | . U+002E |
lower-greek | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+03B1, U+03B2, U+03B3, U+03B4, U+03B5, U+03B6, U+03B7, U+03B8, U+03B9, U+03BA, U+03BB, U+03BC, U+03BD, U+03BE, U+03BF, U+03C0, U+03C1, U+03C3, U+03C4, U+03C5, U+03C6, U+03C7, U+03C8, U+03C9 | 24 | . U+002E | How should U+03C2 (final sigma) be treated?
lower-norwegian | a b c d e f g h i j k l m n o p q r s t u v w x y z æ ø å | U+0061, U+0062, U+0063, U+0064, U+0065, U+0066, U+0067, U+0068, U+0069, U+006A, U+006B, U+006C, U+006D, U+006E, U+006F, U+0070, U+0071, U+0072, U+0073, U+0074, U+0075, U+0076, U+0077, U+0078, U+0079, U+007A, U+00E6, U+00F8, U+00E5 | 29 | none |
oromo, ethiopic-halehame-om-et | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+1200, U+1208, U+1218, U+1228, U+1230, U+1238, U+1240, U+1260, U+1270, U+1278, U+1290, U+1298, U+12A0, U+12A8, U+12C8, U+12E8, U+12F0, U+12F8, U+1300, U+1308, U+1320, U+1328, U+1338, U+1330, U+1348 | 25 | ? U+1366 |
sidama, ethiopic-halehame-sid-et | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+1200, U+1208, U+1210, U+1218, U+1228, U+1230, U+1238, U+1240, U+1260, U+1270, U+1278, U+1290, U+1298, U+12A0, U+12A8, U+12C8, U+12E8, U+12F0, U+12F8, U+1300, U+1308, U+1320, U+1328, U+1338, U+1330, U+1348 | 26 | ? U+1366 |
somali, ethiopic-halehame-so-et | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+1200, U+1208, U+1210, U+1218, U+1228, U+1230, U+1238, U+1240, U+1260, U+1270, U+1290, U+12A0, U+12A8, U+12B8, U+12C8, U+12D0, U+12E8, U+12F0, U+1300, U+1308, U+1338, U+1348 | 22 | ? U+1366 |
tigre, ethiopic-halehame-tig | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+1200, U+1208, U+1210, U+1218, U+1228, U+1230, U+1238, U+1240, U+1260, U+1270, U+1278, U+1290, U+12A0, U+12A8, U+12C8, U+12D0, U+12D8, U+12E8, U+12F0, U+1300, U+1308, U+1320, U+1328, U+1338, U+1330, U+1348, U+1350 | 27 | ? U+1366 |
tigrinya-er, ethiopic-halehame-ti-er | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+1200, U+1208, U+1210, U+1218, U+1228, U+1230, U+1238, U+1240, U+1250, U+1260, U+1270, U+1278, U+1290, U+1298, U+12A0, U+12A8, U+12B8, U+12C8, U+12D0, U+12D8, U+12E0, U+12E8, U+12F0, U+1300, U+1308, U+1320, U+1328, U+1330, U+1338, U+1348, U+1350 | 31 | ? U+1366 |
tigrinya-er-abegede, ethiopic-abegede-ti-er | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+12A0, U+1260, U+1308, U+12F0, U+1300, U+1200, U+12C8, U+12D8, U+12E0, U+1210, U+1320, U+1328, U+12E8, U+12A8, U+12B8, U+1208, U+1218, U+1290, U+1298, U+12D0, U+1348, U+1338, U+1240, U+1250, U+1228, U+1230, U+1238, U+1270, U+1278, U+1330, U+1350 | 31 | ? U+1366 |
tigrinya-et, ethiopic-halehame-ti-et | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+1200, U+1208, U+1210, U+1218, U+1220, U+1228, U+1230, U+1238, U+1240, U+1250, U+1260, U+1270, U+1278, U+1280, U+1290, U+1298, U+12A0, U+12A8, U+12B8, U+12C8, U+12D0, U+12D8, U+12E0, U+12E8, U+12F0, U+1300, U+1308, U+1320, U+1328, U+1330, U+1338, U+1340, U+1348, U+1350 | 34 | ? U+1366 |
tigrinya-et-abegede, ethiopic-abegede-ti-et | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+12A0, U+1260, U+1308, U+12F0, U+1300, U+1200, U+12C8, U+12D8, U+12E0, U+1210, U+1320, U+1328, U+12E8, U+12A8, U+12B8, U+1208, U+1218, U+1290, U+1298, U+1220, U+12D0, U+1348, U+1338, U+1240, U+1250, U+1228, U+1230, U+1238, U+1270, U+1278, U+1280, U+1340, U+1330, U+1350 | 34 | ? U+1366 |
upper-alpha, upper-latin | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z | U+0041, U+0042, U+0043, U+0044, U+0045, U+0046, U+0047, U+0048, U+0049, U+004A, U+004B, U+004C, U+004D, U+004E, U+004F, U+0050, U+0051, U+0052, U+0053, U+0054, U+0055, U+0056, U+0057, U+0058, U+0059, U+005A | 26 | . U+002E |
upper-greek | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | U+0391, U+0392, U+0393, U+0394, U+0395, U+0396, U+0397, U+0398, U+0399, U+039A, U+039B, U+039C, U+039D, U+039E, U+039F, U+03A0, U+03A1, U+03A3, U+03A9 | 24 | . U+002E |
upper-norwegian | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Æ Ø Å | U+0041, U+0042, U+0043, U+0044, U+0045, U+0046, U+0047, U+0048, U+0049, U+004A, U+004B, U+004C, U+004D, U+004E, U+004F, U+0050, U+0051, U+0052, U+0053, U+0054, U+0055, U+0056, U+0057, U+0058, U+0059, U+005A, U+00C6, U+00D8, U+00C5 | 29 | none |

4.5. Symbolic

Symbolic systems use a very simple repeating scheme. Each symbol is used in turn, and once the last symbol has been used, the same symbols are used again but in pairs, and then in threes, and then fours, and so on.

<symbolic>
asterisks | footnotes
asterisks
Increasing numbers of asterisks (*, **, ***, ****, ...)
footnotes
Symbols used to denote footnotes (*, ?, ?, ?, ...)

Symbolic systems are detailed in the next table. Like glyphs, they have no suffix.

Symbolic repeating systems
System | Characters | Codepoints | Notes
asterisks | * | U+002A |
footnotes | * ? ? ? | U+002A, U+2051, U+2020, U+2021 | What about U+2042 ASTERISM?

For example, the first 14 digits of the footnotes system are *, ?, ?, ?, **, ??, ??, ??, ***, ???, ???, ???, ****, ????.

4.6. Non-repeating

The last kind of numbering system is non-repeating. These specify a one to one mapping of numbers to UNICODE glyphs. These are only useful for limited ranges of numbers, beyond which user agents must either synthesize the missing glyphs or fall back on the decimal numbering style.

Should we explicitly define the rules for synthesis? Should we forbid synthesis?

<non-repeating>
circled-decimal | circled-lower-latin | circled-upper-latin | dotted-decimal | double-circled-decimal | filled-circled-decimal | parenthesised-decimal | parenthesised-lower-latin

The mappings for each non-repeating system is described below. These numbering systems do not have suffixes, as they typically contain their own punctuation.

Non-repeating systems
System Range Codepoint Mapping
circled-decimal 0-20
Value | 0 | 1 | 2 | ... | 19 | 20
Character | ? | ? | ? | ... | ? | ?
Codepoint | U+24EA | U+2460 | U+2461 | ... | U+2472 | U+2473
circled-lower-latin 1-26
Value | 1 | 2 | 3 | ... | 25 | 26
Character | ? | ? | ? | ... | ? | ?
Codepoint | U+24D0 | U+24D1 | U+24D2 | ... | U+24E8 | U+24E9
circled-upper-latin 1-26
Value | 1 | 2 | 3 | ... | 25 | 26
Character | ? | ? | ? | ... | ? | ?
Codepoint | U+24B6 | U+24B7 | U+24B8 | ... | U+24CE | U+24CF
dotted-decimal 1-20
Value | 1 | 2 | 3 | ... | 19 | 20
Character | ? | ? | ? | ... | ? | ?
Codepoint | U+2488 | U+2489 | U+248A | ... | U+249A | U+249B
double-circled-decimal 1-10
Value | 1 | 2 | 3 | ... | 9 | 10
Character | ? | ? | ? | ... | ? | ?
Codepoint | U+24F5 | U+24F6 | U+24F7 | ... | U+24FD | U+24FE
filled-circled-decimal 11-20
Value | 11 | 12 | 13 | ... | 19 | 20
Character | ? | ? | ? | ... | ? | ?
Codepoint | U+24EB | U+24EC | U+24ED | ... | U+24F3 | U+24F4
parenthesised-decimal 1-20
Value | 1 | 2 | 3 | ... | 19 | 20
Character | ? | ? | ? | ... | ? | ?
Codepoint | U+2474 | U+2475 | U+2476 | ... | U+2486 | U+2487
parenthesised-lower-latin 1-26
Value | 1 | 2 | 3 | ... | 25 | 26
Character | ? | ? | ? | ... | ? | ?
Codepoint | U+249C | U+249D | U+249E | ... | U+24B4 | U+24B5

Note: The following systems and UNICODE characters have not been given keywords: The superscript and subscript digits (starting at U+2070), the tag characters (starting at U+E0001), the variation forms of latin and greek characters (starting at U+1D400), the halfwidth and fullwidth forms (starting at U+FF01), most of the dingbats (starting at U+2701, including about 64 different star-like bullets, a dozen square bullets, three different kinds of circled decimal digits, as well as a sleuth of arrows and icons like pens and pencils), any of the miscellaneous symbols (starting at U+2600, including numbered recycled symbols, die faces, and many other icons), some of the General Punctuation bullets (e.g. hyphens and dashes at U+2010 to U+2015, triangular bullets starting at U+2023), most of the geometric shapes (starting at U+25A0, including U+25C9), all the enclosed cjk letters and months (starting at U+3200), hangzhou-style numerals (U+3021 to U+3029), the traditional greek numbering systems, the new ethiopic romanised Oromo system Qubee, korean, korean-hangul, korean-check, coptic, and probably many others.

4.7. Unsupported list styles

A user agent that does not recognize a numbering system should ignore the declaration in which the numbering system is used.

For example, the following HTML document:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
 <HEAD>
  <TITLE>Lowercase latin numbering</TITLE>
  <STYLE type="text/css">
   OL { list-style-type: lower-roman; list-style-type: ethiopic-halehame-om-et; }
  </STYLE>
 </HEAD>
 <BODY>
  <OL>
   <LI> This is the first item.
   <LI> This is the second item.
   <LI> This is the third item.
  </OL>
 </BODY>
</HTML>

might produce something like this in a user agent that does not support the ethiopic-halehame-om-et list style type:

   i. This is the first item.
  ii. This is the second item.
 iii. This is the third item.

Note that the list marker alignment (here, right justified) depends on the user agent style sheet's rules for the ::marker pseudo-element.

5. List Content: The 'list-style-image' property

POWERED BY HeroNote
Name: | 'list-style-image'
Value: | <uri> | none
Initial: | none
Applies to: | all elements with 'display: list-item'
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value
Depends on: | none

This property sets the image that will be used as the list item marker. When the image is available, it will replace the marker set with the 'list-style-type' marker.

The following example sets the marker at the beginning of each list item to be the image "ellipse.png".

LI { list-style-image: url("http://www.example.com/ellipse.png") }

6. List Content: Generating the computed value of the 'content' property

If a ::marker pseudo-element has its 'content' property set to normal, the following algorithm should be used to generate the computed value of the property. Note that there being a computed value of the 'content' property is not enough for the ::marker pseudo-element to be rendered. See the section on the 'list-style-position' property below.

  1. If 'list-style-image' is not 'none', and if the image is valid, then the content is the value of the 'list-style-image' property.
  2. Otherwise, if the list-style-type property is not 'none', then the computed value of the 'content' property is counter(list-item, <list-style-type>) followed by a string, where <list-style-type> is the computed value of the 'list-style-type' property, or the default style type for the list-item counter if the 'list-style-type' has the value 'normal', and the string is the suffix for the list style type in question (which may be empty).
  3. Otherwise the computed value is inhibit. (Note: This is not the same as the empty string, nor the same as none.)

Ths algorithm may be superseded by a more detailed algorithm given in the Generated and Replaced Content module, when it is released.

Given the following style sheet:

li { display: list-item; list-style-type: decimal /* initial value */; }
li::marker { content: normal /* initial value */; }

And the following document fragment:

<li> List Item </li>

The computed value of the 'content' property on the ::marker pseudo-element of the list item element is:

counter(list-item, decimal) '\002E'

7. Marker Position: The 'list-style-position' property

Name: | 'list-style-position'
Value: | inside | outside
Initial: | outside
Applies to: | all elements with 'display: list-item'
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value
Depends on: | none

This property specifies the position of the marker box in the principal block box. Values have the following meanings:

outside
The marker box is outside the principal block box, as described in the section on the ::marker pseudo-element below.
inside
The ::marker pseudo-element is an inline element placed immediately before all ::before pseudo-elements in the principal block box, after which the element's content flows. Note that if there is no inline content, this will create a line box, just as content in an inline ::before pseudo-element would. Also note that all the properties that apply to inline elements apply to the ::marker pseudo-element in this state, and this ::marker box participates in the inline box model in the normal manner.

Note that a marker is only generated if the computed value of the 'content' property for the element's ::marker pseudo-element is not inhibit.

For example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
 <HEAD>
  <TITLE>Comparison of inside/outside position</TITLE>
  <STYLE type="text/css">
   UL         { list-style: outside }
   UL.compact { list-style: inside }
  </STYLE>
 </HEAD>
 <BODY>
  <UL>
   <LI>first list item comes first</LI>
   <LI>second list item comes second</LI>
  </UL>
  <HT>
  <UL class="compact">
   <LI>first list item comes first</LI>
   <LI>second list item comes second</LI>
  </UL>
 </BODY>
</HTML>

The above example may be formatted as:

list with bullets to the left of it and list with bullets inside

In right-to-left text, the markers would have been on the right side of the box.

8. The 'list-style' shorthand property

Name: | 'list-style'
Value: | [ <'list-style-type'> || <'list-style-position'> || <'list-style-image'> ]
Initial: | not defined for shorthand properties
Applies to: | all elements with 'display: list-item'
Inherited: | not defined for shorthand properties
Percentages: | N/A
Media: | visual
Computed value: | not defined for shorthand properties
Depends on: | none

The 'list-style' property is a shorthand notation for setting the three properties 'list-style-type', 'list-style-image', and 'list-style-position' at the same place in the style sheet.

For example:

UL { list-style: upper-roman inside }  /* Any UL */
UL > UL { list-style: circle outside } /* Any UL child of a UL */

Although authors may specify 'list-style' information directly on list item elements (e.g., LI in HTML), they should do so with care. The following rules look similar, but the first declares a descendant selector and the second a (more specific) child selector.

OL.alpha LI   { list-style: lower-alpha } /* Any LI descendant of an OL */
OL.alpha > LI { list-style: lower-alpha } /* Any LI child of an OL */

Authors who use only the descendant selector may not achieve the results they expect. Consider the following rules:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
 <HEAD>
  <TITLE>WARNING: Unexpected results due to cascade</TITLE>
  <STYLE type="text/css">
   OL.alpha LI  { list-style: lower-alpha }
   UL LI        { list-style: disc }
  </STYLE>
 </HEAD>
 <BODY>
  <OL class="alpha">
   <LI>level 1
    <UL>
     <LI>level 2</LI>
    </UL>
   </LI>
  </OL>
 </BODY>
</HTML>

The desired rendering would have level 1 list items with 'lower-alpha' labels and level 2 items with 'disc' labels. However, the cascading order will cause the first style rule (which includes specific class information) to mask the second. The following rules solve the problem by employing a child selector instead:

OL.alpha > LI   { list-style: lower-alpha }
UL LI           { list-style: disc }

Another solution would be to specify 'list-style' information only on the list type elements:

OL.alpha   { list-style: lower-alpha }
UL         { list-style: disc }

Inheritance will transfer the 'list-style' values from OL and UL elements to LI elements. This is the recommended way to specify list style information.

A URI value may be combined with any other value, as in:

UL { list-style: url("http://png.com/ellipse.png") disc }

In the example above, the 'disc' will be used when the image is unavailable.

A value of 'none' for the 'list-style' property sets both 'list-style-type' and 'list-style-image' to 'none', because it sets the 'list-style-type' to none (that is the first value in the list), and the initial value of the 'list-style-image' property, which isn't listed in that declaration, is none. For this reason,

LI { list-style: none; }

will ensure that no list-item marker is displayed on LI elements, except if a value is explicitly given to the 'content' property of the ::marker pseudo-element. In general, the best way to ensure that no marker is rendered is to not set the 'display' property to list-item.

9. Markers: The ::marker pseudo-element

Markers are created by setting an element's 'display' property to list-item. The list-item display type is, in every other respect, identical to the block display type.

The marker box is only created if the computed value of the 'content' property for the pseudo-element is not inhibit. The rest of this section discusses the details of the positioning of the marker box if it is positioned outside. For details on positioning the marker box when it is an inside list marker, see the section on 'list-style-position'.

If the elements' 'list-style-position' property has the value outside, then the value of the element's ::marker pseudo-element's 'content' property is formatted in an independent marker box, outside the principal box. Marker boxes are formatted as an inline-block (i.e., they fit in one line box), so they are not as flexible as floats or absolutely positioned boxes.

Marker boxes have padding, borders and margins, just like inline-block elements. The marker box will be vertically aligned with the first line of content in the principal box, as specified by the pseudo-element's 'vertical-align' property. The marker box participates in the height calculation of the principal box's first line box. Thus, markers are aligned with the first line of an element's content. If no first line box exists in a principal box, the marker box establishes its line box alone. (The first line of a principle box is the one matched by the box's '::first-line' pseudo-element.)

The marker box is horizontally aligned with the start of the line box. Thus if a float intersects the element, moving the line box start, the marker box is moved as well. It is the responsibility of the author to ensure that sufficient margins are provided to prevent marker boxes overlapping with the floats. If the marker box is generating the line box, then it is aligned with the content area's start edge. The box model defines the properties 'float-displace' and 'indent-edge-reset' to control how far line boxes are moved in the presence of floats.

If the value of the 'width' property is auto, the marker box content width is that of the content, otherwise it is the value of 'width'. For values of 'width' less than the content width, the overflow is visible. The 'overflow' property does not apply. The 'text-align' property determines the horizontal alignment of the content in the marker box.

Marker boxes may overlap principal boxes and other marker boxes. Overlap could happen for several reasons. If several nested elements without inline content all have marker boxes, for instance, or if a marker box has negative margins. Marker boxes are rendered at the same stack level as inline content of the principle box, as if it was the first box of the first line box.

The CSS2 'marker-offset' property is obsoleted in this model and has no effect. (It is replaced by the 'margin-right' property in left-to-right text, and the 'margin-left' property in right-to-left text.)

In the following example, the content is centered within a marker box of a fixed width. This document:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
 <HEAD>
  <TITLE>Content alignment in the marker box</TITLE>
  <STYLE type="text/css">
   LI::marker {
     content: "(" counter(counter) ")";
     width: 6em;
     text-align: center;
   }
   LI {
     display: list-item;
     counter-increment: counter;
   }
  </STYLE>
 </HEAD>
 <BODY>
  <OL>
   <LI> This is the first item. </LI>
   <LI> This is the second item. </LI>
   <LI> This is the third item. </LI>
  </OL>
 </BODY>
</HTML>

should produce something like this:

  (1)    This is the
         first item.
  (2)    This is the
         second item.
  (3)    This is the
         third item.

The next example uses markers to number notes (paragraphs).

The following document:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
 <HEAD>
  <TITLE>Markers to create numbered notes4>/TITLE>
  <STYLE type="text/css">
   P { margin-left: 12 em; }
   P.Note::marker {
      content: url("note.gif") "Note " counter(note-counter) ":";
      text-align: left;
      width: 10em;
   }
   P.Note {
     display: list-item;
     counter-increment: note-counter;
   }
  </STYLE>
 </HEAD>
 <BODY>
  <P>This is the first paragraph in this document.</P>
  <P CLASS="Note">This is a very short document.</P>
  <P>This is the end.</P>
 </BODY>
</HTML>

should produce something like:

            This is the first paragraph
            in this document.

  Note 1:   This is a very short
            document.

            This is the end.

The following example illustrates how markers may be offset from their element. This HTML application and style sheet:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE>Marker example 5</TITLE>
  <STYLE type="text/css">
   P { margin-left: 8em } /* Make space for counters */
   LI::marker { margin: 0 3em 0 0; content: counter(list-item, lower-roman) "."; }
   LI { display: list-item }
  </STYLE>
 </HEAD>
 <BODY>
  <P> This is a long preceding paragraph ...</P>
  <OL>
   <LI> This is the first item.
   <LI> This is the second item.
   <LI> This is the third item.
  </OL>
  <P> This is a long following paragraph ...</P>
 </BODY>
</HTML>

should produce something like this:

        This is a long preceding
        paragraph ...

   i.   This is the first item.
  ii.   This is the second item.
 iii.   This is the third item.

        This is a long following
        paragraph ...

(Note the use of the implicit counter increment.)

10. Profiles

This module has two profiles: CSS Level 1 and Full. There is no CSS2 profile because this module is incompatible with the CSS2 list model.

The CSS Level 1 module consists of 'list-style', 'list-style-position', 'list-style-image', and 'list-style-type' (but only the following values: 'disc', 'circle, square', 'decimal', 'lower-roman', 'upper-roman', 'lower-alpha', 'upper-alpha', 'none'). It does not include the ::marker pseudo element.

The Full profile contains everything.

11. Sample style sheet for HTML 4.0

This section is informative, nor normative.

 /* Set up list items */
 li { display: list-item; /* counter-increment: list-item; (implied by display: list-item) */ }

 /* Set up ol and ul so that they reset the list-item counter */
 ol, ul { counter-reset: list-item; }

 /* Default list style types for ordered lists */
 ol { list-style-type: decimal; }

 /* Default list style types for unordered lists up to 3 deep */
 ul { list-style-type: disc; }
 ul ul { list-style-type: square; }
 ul ul ul { list-style-type: circle; }

 /* The type attribute on ol and ul elements */
 ul[type="disc"] { list-style-type: disc; }
 ul[type="circle"] { list-style-type: circle; }
 ul[type="square"] { list-style-type: square; }
 ol[type="1"] { list-style-type: decimal; }
 ol[type="a"] { list-style-type: lower-alpha; }
 ol[type="A"] { list-style-type: upper-alpha; }
 ol[type="i"] { list-style-type: lower-roman; }
 ol[type="I"] { list-style-type: upper-roman; }

 /* The start attribute on ol elements */
 ol[start] { counter-reset: list-item attr(start, integer, 1); counter-increment: list-item -1; }

 /* The value attribute on li elements */
 li[value] { counter-reset: list-item attr(value, integer, 1); counter-increment: none; }

 /* The above rules don't fully describe HTML4 lists, since they do not cover
    behaviors such as margins and the like. The following rules could be used
    for this purpose:

    ol, ul { display: block; margin: 1em 0; padding-left: 2.5em; }
    ol ol, ol ul, ul ul, ul ol { margin-top: 0; margin-bottom: 0; }
    li::marker { margin-right: 1em; text-align: right; }

  */

Another example is required here.

Acknowledgments

The following people and documentation they wrote were very useful for defining the numbering systems: Alexander Savenkov, Frank Tang, Jonathan Rosenne, Karl Ove Hufthammer, Musheg Arakelyan, and Randall Bart.

Changes From CSS2

As described in the introduction section, there are significant changes in this module when compared to CSS2.

  1. display:marker has been replaced with ::marker
  2. It is no longer possible to make end markers.
  3. The 'marker-offset' property is obsoleted.
  4. The marker display type is obsoleted.
  5. Markers are now aligned relative to the line box edge, rather than the border edge.
  6. Markers now have margins.
  7. The introduction of many new list style types as well as explicit algorithms for all list style types.
  8. Error handling rules for unknown list style types were changed to be consistent with the normal parsing error handling rules.
  9. The list-item predefined counter identifier has been introduced.

References

Normative references

[CSS3BOX]
Bert Bos. CSS3 module: box model. 26 July 2001. W3C working draft. (Work in progress.) URL: http://www.w3.org/TR/2001/WD-css3-box-20010726
[CSS3GENCON]
Håkon Wium Lie; Ian Hickson. CSS3 module: generated text. (forthcoming). W3C working draft. (Work in progress.)
[CSS3LINE]
Eric A. Meyer. CSS3 module: linebox model. (forthcoming). W3C working draft. (Work in progress.)
[CSS3SYN]
David Baron. CSS3 module: syntax. (forthcoming). W3C working draft. (Work in progress.)
[CSS3VAL]
Håkon Wium Lie. CSS3 module: values and units. (forthcoming). W3C working draft. (Work in progress.)
[SELECT]
Daniel Glazman; Tantek Çelik; Ian Hickson; et al. Selectors. 13 Nov 2001. W3C Candidate Recommendation. URL: http://www.w3.org/TR/2001/CR-css3-selectors-20011113

Other references

[CSS3INTRO]
Eric A. Meyer; Bert Bos. Introduction to CSS3. 23 May 2001. W3C working draft. (Work in progress.) URL: http://www.w3.org/TR/css3-roadmap

Index

  • afar, #
  • amharic, #
  • amharic-abegede, #
  • arabic-indic, #
  • armenian, #
  • asterisks, #, #
  • auto, #
  • bengali, #
  • binary, #
  • box, #
  • cambodian, #
  • check, #
  • circle, #
  • circled-decimal, #
  • circled-lower-latin, #
  • circled-upper-latin, #
  • cjk-earthly-branch, #
  • cjk-heavenly-stem, #
  • cjk-ideographic, #
  • decimal, #
  • decimal-leading-zero, #
  • devanagari, #
  • diamond, #
  • disc, #
  • dotted-decimal, #
  • double-circled-decimal, #
  • ethiopic, #
  • ethiopic-abegede, #
  • ethiopic-abegede-am-et, #
  • ethiopic-abegede-gez, #
  • ethiopic-abegede-ti-er, #
  • ethiopic-abegede-ti-et, #
  • ethiopic-halehame-aa-er, #
  • ethiopic-halehame-aa-et, #
  • ethiopic-halehame-am-et, #
  • ethiopic-halehame-gez, #
  • ethiopic-halehame-om-et, #
  • ethiopic-halehame-sid-et, #
  • ethiopic-halehame-so-et, #
  • ethiopic-halehame-ti-er, #
  • ethiopic-halehame-ti-et, #
  • ethiopic-halehame-tig, #
  • ethiopic-numeric, #
  • filled-circled-decimal, #
  • footnotes, #, #
  • georgian, #
  • gujarati, #
  • gurmukhi, #
  • hangul, #
  • hangul-consonant, #
  • hebrew, #
  • hiragana, #
  • hiragana-iroha, #
  • hyphen, #
  • inside, #
  • japanese-formal, #
  • japanese-informal, #
  • kannada, #
  • katakana, #
  • katakana-iroha, #
  • khmer, #
  • lao, #
  • 'list-style', #
  • 'list-style-image', #
  • 'list-style-position', #
  • 'list-style-type', #
  • lower-alpha, #
  • lower-armenian, #
  • lower-greek, #
  • lower-hexadecimal, #
  • lower-latin, #
  • lower-norwegian, #
  • lower-roman, #
  • <algorithmic>, #
  • <alphabetic>, #
  • <glyph>, #
  • <non-repeating>, #
  • <numeric>, #
  • <symbolic>, #
  • malayalam, #
  • mongolian, #
  • myanmar, #
  • normal, #
  • octal, #
  • oriya, #
  • oromo, #
  • outside, #
  • parenthesised-decimal, #
  • parenthesised-lower-latin, #
  • persian, #
  • sidama, #
  • simp-chinese-formal, #
  • simp-chinese-informal, #
  • somali, #
  • square, #
  • syriac, #
  • tamil, #
  • telugu, #
  • thai, #
  • tibetan, #
  • tigre, #
  • tigrinya-er, #
  • tigrinya-er-abegede, #
  • tigrinya-et, #
  • tigrinya-et-abegede, #
  • trad-chinese-formal, #
  • trad-chinese-informal, #
  • upper-alpha, #
  • upper-armenian, #
  • upper-greek, #
  • upper-hexadecimal, #
  • upper-latin, #
  • upper-norwegian, #
  • upper-roman, #
  • urdu, #


CSS3 Module- Paged Media

POWERED BY HeroNote

CSS3 Module: Paged Media

W3C Working Draft 10 October 2006

This version:
http://www.w3.org/TR/2006/WD-css3-page-20061010
Latest version:
http://www.w3.org/TR/css3-page
Previous version:
http://www.w3.org/TR/2004/CR-css3-page-20040225/
Editors:
Håkon Wium Lie, Opera Software
Melinda Grant, Hewlett-Packard

Copyright © 2006 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

This module describes the page model that partitions a flow into pages. It builds on the Box model module and introduces and defines the page model and paged media. It adds functionality for pagination, page margins, page size and orientation, headers and footers, widows and orphans, and image orientation. Finally it extends generated content to enable page numbering and running headers / footers.

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css3-page” in the subject, preferably like this: “[css3-page] …summary of comment…”

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document contains the CSS3 Paged Media Module W3C Last Call Working Draft of 10 October 2006. The Last Call period ends on 3 November 2006.

Relative to the previous Candidate Recommendation, this version removes page-based floats, string-set, and page-policy features, which have been moved to CSS3 Generated Content for Paged Media; adds two new features ('fit' and 'fit-position'); and incorporates a new algorithm for determining margin box sizes as well as miscellaneous clarifications and editorial improvements.

Table of Contents

  • 1. Dependencies on other CSS Modules
  • 2. Introduction
    • 2.1. Terminology
  • 3. Page Boxes: the @page Rule
    • 3.1. Page Terminology and the Page Model
    • 3.2. Page types
    • 3.3. Page size
      • 3.3.1. Page size: the 'size' property
      • 3.3.2. Media Queries
      • 3.3.3. Rendering page boxes that do not fit a page sheet
      • 3.3.4. Positioning the page box on the sheet
    • 3.4. Page Selectors and the Page Context
      • 3.4.1. Page selector grammar
      • 3.4.2. Cascading in the page context
    • 3.5. Page Properties
    • 3.6. Left, right, and first pages
    • 3.7. Content outside the page box
  • 4. Margin Boxes
    • 4.1. At-rules for margin boxes
    • 4.2. Maximum Dimension of margin boxes
    • 4.3. Dimension of margin boxes
    • 4.4. Margin boxes and default values
      • 4.4.1. Margin box examples
    • 4.5. Populating margin boxes
  • 5. Page Breaks
    • 5.1. Break before/after elements: 'page-break-before', 'page-break-after', 'page-break-inside'
    • 5.2. Using named pages: 'page'
    • 5.3. Breaks inside elements: 'orphans', 'widows'
    • 5.4. Allowed page breaks
    • 5.5. Forced page breaks
    • 5.6. "Best" page breaks
  • 6. Page-based Extensions to Counters
    • 6.1. Page-based counters
  • 7. Orienting an Image on the Page
  • 8. The 'fit' and 'fit-position' Properties
  • References
    • Normative References
    • Informative References

1. Dependencies on other CSS Modules

This CSS3 module depends on Cascading Style Sheets Level 2 Revision 1 [CSS21] for all underlying requirements such as syntax, selectors, box model, fonts, etc. It may in the future be updated to depend on other CSS3 modules rather than on CSS 2.1.

2. Introduction

Paged media (e.g., paper, transparencies, pages that are displayed on computer screens, etc.) differ from continuous media in that the content of the document is split into one or more discrete static display surfaces. To handle pages, CSS3 Paged Media describes how:

  • page breaks are created and avoided,
  • the page properties such as size, orientation, margins, border, and padding are specified,
  • headers and footers are established within the page margins,
  • content such as page counters are placed in the headers and footers, and
  • orphans and widows can be controlled.

CSS3 defines a page model that specifies how a document is formatted within a rectangular area, called the page box, that has finite width and height. Often, but not always, the page box has a one-to-one correspondence to a physical sheet onto which the document is ultimately rendered (paper, transparency, screen etc.). The CSS3 page model specifies formatting within the page box, but it is the user agent's responsibility to transfer the page box to the sheet. Some user agent transfer possibilities that are not addressed by CSS3 include:

  • Transferring one page box to one sheet (e.g. single-sided printing);
  • Transferring two page boxes to the front and back surfaces of the same sheet (e.g. double-sided printing);
  • Transferring N (small) page boxes to one sheet (called "N-up");
  • Transferring one (large) page box to N x M sheets (called "tiling");
  • Creating signatures. A signature is a group of pages printed on a sheet, which, when folded and trimmed like a book, appear in their proper sequence;
  • Printing one document to multiple output trays;
  • Generating files containing print instructions.

Although CSS3 does not specify how user agents transfer page boxes to sheets, it does include certain mechanisms for telling user agents about the intended page sheet size and orientation. In the general case, CSS3 assumes that one page box will be transferred to one surface of a sheet of similar size.

2.1. Terminology

The keywords "MUST", "SHALL", "MUST NOT", "SHALL NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" when used in this document are to be interpreted as described in RFC 2119 [RFC2119]. However, for readability, these words do not appear in all uppercase letters in this specification.

3. Page Boxes: the @page Rule

In the page model, the document is transferred into one or more page boxes. The page box is a specialized CSS box that maps to a rectangular print media surface. It is roughly analogous to the viewport. As for other boxes, a page box consists of margin, border, padding, and content areas. The content and margin areas of a page box have special functions:

  • The content area of a page box is called the page area. The content of the document is flowed into the page area. The edges of the page area on the first page establish the rectangle that is the initial containing block of the document.
  • The margin area of a page box is divided into 16 margin boxes. Each margin box has its own margin, border, padding and content areas. Margin boxed are typically used to display running headers and footers.

The properties of a page box are determined by properties established within the page context, which is the rule set of the @page rule. Page boxes differ from other boxes in that the 'width' and 'height' properties do not apply to a page box. The size of the page box is specified using the 'size' property in the page context.

3.1. Page Terminology and the Page Model

The following terminology and accompanying diagrams help to describe the page model:

Page sheet
The corner of a page sheet with the non-printable area at the edge and printable area inside it The page sheet is one surface of the physical medium. The illustration to the right shows a representation of the upper-left corner of a page sheet.
Non-printable area
The non-printable area is the area of a page sheet that a physical device such as a printer is not capable of marking reliably, usually due to the printer's paper handling mechanism. This value is printer dependent and is usually a small area along each edge of the page sheet. The unprintable region along the left and right edges of the page are usually the same size, as are the top and bottom areas. However, the top/bottom and left/right areas can be different. A user agent may not be aware of this area or how it varies from device to device. Printing devices MAY adjust the layout of the document so that content is not lost. How this adjustment is accomplished is device dependent within the constraints expressed in the sections Rendering page boxes that do not fit a page sheet and Content outside the page box.
Printable area
The printable area is the area of page sheet that a printer is capable of marking reliably. The size of the printable area is the size of the page sheet reduced by the size of the non-printable area. This value is printing device dependent. A user agent may not be aware of this area or how it varies from printing device to printing device. Printing devices MAY adjust the layout of the document so that content falls within the printable area. How this adjustment is accomplished is device dependent within the constraints expressed in the sections Rendering page boxes that do not fit a page sheet and Content outside the page box.
Page box
Illustration of the page box with page area nested within the page padding that is within page border that is within the page margin A page box is derived from the box model and contains portions of the document flow destined for rendering on a page sheet. The width and height of the page box are determined by the size property. Unlike other boxes, the margins of the page box are subdivided into margin boxes. In the simplest case, the page box is congruent with the page sheet. However, there are more complex use cases (see the transfer possibilities in the Introduction) where the page box differs from the page sheet in values such as size or orientation.
Page area
The page area is a synonym for the content area of the page box. The page area acts as a container for all the boxes laid out within a given page box.
Margin box
Margin boxes act as containing boxes for header/footer content. The following margin boxes are defined and illustrated in the diagram below:
Table 1 Margin Box Definitions
Box | Description | Placement
top-left-corner | a fixed-size box filling the area defined by the intersection of the top and left margins of the page box | the top left corner box with margin, border, and padding, nested within intersection of the page's top and left margins
top-left | a variable-width box within the area defined by the top margin and adjoining the top-left-corner margin box | the top left box with margin, border, and padding, nested in the page's top margin next to the top left corner box
top-center | a variable-width box within the area defined by the top margin, centered on the page area, and between the top-left and top-right margin boxes | the top center box with margin, border, and padding, centered within the page's top margin
top-right | a variable-width box within the area defined by the top margin and adjoining the top-right-corner margin box | the top right box with margin, border, and padding, nested within the page's top margin
top-right-corner | a box filling the area defined by the intersection of the top and right margins of the page box | the top right corner box with margin, border, and padding, nested within the intersection of the page's top and right margin
left-top | a variable-height box within the area defined by the left margin and adjacent to the bottom of the top-left-corner. | left-top, left-middle, and left-bottom margin boxes in the page box's left margin
left-middle | a variable-height box in the area defined by the left margin, centered on the page area, and between the left-top and left-bottom margin boxes.
left-bottom | a variable-height box within the area defined by the left margin and adjacent to the top of the bottom-left-corner.
right-top | a variable-height box within the area defined by the right margin and adjacent to the bottom of the top-right-corner. | right-top, right-middle, and right-bottom margin boxes in the page box's right margin
right-middle | a variable-height box in the area defined by the right margin, centered on the page area, and between the right-top and right-bottom margin boxes.
right-bottom | a variable-height box within the area defined by the right margin and adjacent to the top of the bottom-right-corner.
bottom-left-corner | a box filling the area defined by the intersection of the bottom and left margins of the page box | bottom left corner box with margin, border, and padding, nested within the page margin at the intersection of the left and bottom page margins
bottom-left | a variable-width box within the area defined by the bottom margin and adjoining the bottom-left-corner margin box | bottom left margin box with margin, border, and padding, nested within the page's bottom margin next to the bottom-left-corner box
bottom-center | a variable-width box within the area defined by the bottom margin, centered on the page area, and between the bottom-left and bottom-right margin boxes | bottom center box with margin, border, and padding, nested within the page's bottom margin and centered on the page
bottom-right | a variable-width box within the area defined by the bottom margin and adjoining the bottom-right corner margin box | bottom right margin box with margin, border, and padding, nested within the page's bottom margin and next to the bottom-right-corner box
bottom-right-corner | a box filling the area defined by the intersection of the bottom and right margins of the page box | bottom right corner box with margin, border, and padding, nested within the page margin at the intersection of the right and bottom page margins
Content-empty Page
a page surface whose page area contains no printable content other than backgrounds and/or borders. A page containing generated content or invisible content such as a zero-width space within the page area is not a content-empty page. On the other hand, a page containing only a background and/or borders and/or padding and/or margin-box content is a content-empty page.

3.2. Page types

Page layouts have many possible realizations. Among the aspects of page layout that can vary are paper size, orientation of the layout with respect to the paper, order of the pages, how the document will be printed, and how the document will be bound. Some of these depend upon factors such as the major writing direction and the media type that are not specified by this module. The following terminology is used to describe pages and page treatments:

Page Orientation
The page orientation is defined by comparing the length of the edges of a page box. The page box is a rectangle with two perpendicular edges called the long edge and the short edge. The length of the long edge is always greater than or equal to the length of the short edge. When the page box is square, the two edges are of the same length and either can be used as the long edge with the other being the short edge.
Portrait Orientation
A portrait page's height is greater than or equal to its width. Horizontal elements are parallel to the short edge and vertical elements to the long edge.
Landscape Orientation
A landscape page's width is greater than or equal to its height. Horizontal elements are parallel to the long edge and vertical elements to the short edge.
Front Side
Media used as a stack of sheets have two sides known as the front and the back. Typically, the user agent prints on the front side of the media when using only one side of the page sheet. Media used from a roll or continuous form will print only on the front side. CSS does not provide a mechanism to deal directly with the front and back sides, rather page layouts must be designed in terms of left and right pages.
Back Side
The back side of a sheet medium is the side that cannot be seen when looking at the front side. Typically, the back side is only used when printing on both sides of the medium. Unless using special paper stock such as letterhead it does not usually matter which side is the front and which is the back.
Duplex Printing
Duplex printing uses one page box per side of a page sheet and uses both sides of the page sheet. This module provides no ability to specify whether a document is duplex printed, but the concept of left and right pages is based on the assumption that the document is duplex printed, regardless of whether it actually is.
Binding Edge treatment
The binding edge is the edge of the page box that is towards the binding if the material is bound. The binding edge often has a larger margin than the opposite edge to provide for the space used by the binding. The binding edge can be any of the four edges. However, page sheets are customarily bound so that the binding edge of page boxes with portrait orientation is vertical. This module provides no method to specify the binding edge. In duplex printing, the binding edge is on opposite sides of the page box for the left and right pages.
Facing Pages
Facing pages are two sequential pages such that when the document is duplex printed they are on separate sheets of paper. Typically, the earlier page will be the back side of one sheet and the later page will be the front side of another. They are usually laid out so that the binding edges of facing pages are vertical and adjacent when the pages are placed in their normal reading orientation. It is up to the UA to determine whether the left page or the right page of a pair of facing pages is the earlier one of the sequence. How the UA makes this determination is implementation dependent but often depends upon the predominant writing direction of the document.
Major Writing Direction
The major writing direction for the document is determined by the UA. If the UA supports the 'direction' property from CSS2 or the CSS 3 Text Module it MUST determine it using the value of that property on the root element.
Left Page
A page that will be on the left if it is part of a pair of facing pages as typically laid out. Page layouts for documents using a left-to-right major writing direction have the earlier of the facing pages on the left. Rules for the left page can be specified using the ':left' page selector.
Right Page
A page that will be on the right if it is part of a pair of facing pages as typically laid out. Page layouts for documents using a right-to-left major writing direction have the earlier of the facing pages on the right. Rules for the right page can be specified using the ':right' page selector.
First Page
The first page in a document. The first page is generally printed on the front side of a medium. Rules for the first page can be specified using the ':first' page selector. A first page can be either a left page or a right page but a UA MUST apply any rules defined for a first page in preference to those defined on a left page or a right page.

3.3. Page size

Different parts of the world use different paper sizes. It is a goal of this specification that web content should be adaptable to a range of different sizes without having to write a specific style sheet for each paper size.

However, in some situations it is important that a certain page size achieves a certain style. One way to achieve this goal is to utilize the 'size' property, which requests that the document is printed on a page which has a certain size; another method is to use Media Queries [MEDIAQ] which allow different style sheets to be applied to different page sizes.

3.3.1. Page size: the 'size' property

Name: | size
Value: | <length>{1,2} | auto | [ <page-size> || [ portrait | landscape] ]
Initial: | auto
Applies to: | page context
Inherited: | N/A
Percentages: | N/A
Media: | paged
Computed value: | specified value

This property specifies the size and orientation of the containing box for page content, the page box. In the general case, where one page box is rendered onto one page sheet, the 'size' property also indicates the size of the destination page sheet.

The size of a page box MAY either be "absolute" (fixed size) or "relative" (scalable, i.e., fitting available sheet sizes). Relative page boxes allow user agents to scale a document and make optimal use of the page size.

Three values for the 'size' property create a relative page box:

auto
The page box will be set to the size and orientation of the page sheet chosen by the UA.
landscape
Specifies that the page's content be printed in landscape orientation. The page box is the same size as the page, and the longer sides are horizontal. If a '<length>' or '<page-size>' is not specified, the size of the page sheet is chosen by the UA.
portrait
Specifies that the page's content be printed in portrait orientation. The page box is the same size as the page, and the shorter sides are horizontal. If a '<length>' or '<page-size>' is not specified, the size of the page sheet is chosen by the UA.

In the following example, the outer edges of the page box will align with the page. The percentage value on the 'margin' property is relative to the page size so if the page sheet dimensions are 210mm x 297mm (i.e., A4), the margins are 21mm and 29.7mm.

@page {
  size: auto;/* auto is the initial value */
  margin: 10%;
}

Other values define a fixed-size page box, and thereby indicate the preferred output media size. When possible, output should be rendered on the media size indicated; if not available, a larger size should be used; if not available, the contents of the page box should be scaled down to fit the smaller page sheet.

<length>
The page box will be set to the given absolute length. If only one length value is specified, it sets both the width and height of the page box (i.e., the box is a square). The page context has a font associated with it either by an explicit use of the 'font-family' and 'font-size' properties or from the UA's default style sheet. Therefore, values in units of 'em' and 'ex' refer to the page context's font.

For example:

@page {
  size: 8.5in 11in;/* width height */
}

The above example sets the width of the page box to be 8.5 inches and the height to be 11 inches. The page box in this example requires a page sheet size of 8.5"x11" or larger.

<page-size>
A page size can be specified using one of the following media names. This is the equivalent of specifying the '<page-size>' using length values. The definition of the the media names comes from Media Standardized Names [PWGMSN].
A5
The page box SHOULD be set to the size of ISO A5 media: 148mm wide and 210 mm high.
A4
The page box SHOULD be set to the size of IS0 A4 media: 210 mm wide and 297 mm high.
A3
The page box SHOULD be set to the size of ISO A3 media: 297mm wide and 420mm high.
B5
The page box SHOULD be set to the size of ISO B3 media: 176mm wide by 250mm high.
B4
The page box SHOULD be set to the size of ISO B4 media: 250mm wide by 353mm high.
letter
The page box SHOULD be set to the size of North American letter media: 8.5 inches wide and 11 inches high
legal
The page box SHOULD be set to the size of North American legal: 8.5 inches wide by 14 inches high.
ledger
The page box SHOULD be set to the size of North American ledger: 11 inches wide by 17 inches high.

These media size names can be used in conjunction with 'landscape' or 'portrait' to indicate size and orientation.

For example:

@page {
  size: A4 landscape;
}

The above example sets the width of the page box to be 297mm and the height to be 210mm. The page box in this example should be rendered on a page sheet size of 210 mm by 297 mm.

User agents SHOULD also support Media Size Self-Describing Names as defined in Section 5 of [PWGMSN].

3.3.2. Media Queries

This section is informative.

By using Media Queries [MEDIAQ], one style sheet can express different stylistic preferences for different page sizes. Consider this example:

   /* style sheet for "A4" printing */
   @media print and (width: 21cm) and (height: 29.7cm) {
      @page {
         margin: 3cm;
      }
   }

   /* style sheet for "letter" printing */
   @media print and (width: 8.5in) and (height: 11in) {
      @page {
          margin: 1in;
      }
   }

In the example above, "A4" sheets are given a "3cm" page margin, and "letter" sheets are given a "1in" page margin.

In Media Queries, the page is always considered to be in Portrait Orientation. That is, it is not necessary to write Media Queries that swap the width and height values to make sure the style sheet is applied.

3.3.3. Rendering page boxes that do not fit a page sheet

If a page box does not match the target page sheet dimensions, the user agent MAY choose (in order of preference) to:

  • Render the page box at the indicated size on a larger page sheet.
  • Rotate the page box 90° if this will make the page box fit the page sheet.
  • Scale the page box to fit the page sheet. (There is no requirement to maintain the aspect ratio of the page or of any elements on the page when scaling; however, preservation of the aspect ratio is preferred.)
  • Reformat the page contents, including 'spilling' onto other page sheets.
  • Clip overflowed content (least preferred).

The user agent SHOULD consult the user before performing these operations.

3.3.4. Positioning the page box on the sheet

When the page box is smaller than the page size, the user agent SHOULD center the page box on the sheet since this will align double-sided pages and avoid accidental loss of information that is printed near the edge of the sheet.

3.4. Page Selectors and the Page Context

Authors specify the dimensions, orientation, margins, etc. of a page box within an @page rule. An @page rule consists of the keyword '@page', an OPTIONAL page name followed with no intervening space by an OPTIONAL page pseudo-class and a block of declarations and margin rules (said to be in the page context).

The OPTIONAL page name and OPTIONAL page pseudo-class constitutes the page selector. The page selector specifies for which pages the declarations apply. In CSS3, page selectors MAY designate the first page of a document, all left pages, all right pages, or pages with specific names.

Properties for the page box are specified within the page context.

3.4.1. Page selector grammar

The syntax for a page selector is a specialization of the generic at-rule and MUST adhere to the following (more strict) grammar:

See [CSS21], Section 4.1.1 and Appendix G for the expansion of missing productions:

All new lexical tokens are specializations of the ATKEYWORD lexical token:

PAGE_SYM              ::= "@page"
TOPLEFTCORNER_SYM     ::= "@top-left-corner"
TOPLEFT_SYM           ::= "@top-left"
TOPCENTER_SYM         ::= "@top-center"
TOPRIGHT_SYM          ::= "@top-right"
TOPRIGHTCORNER_SYM    ::= "@top-right-corner"
BOTTOMLEFTCORNER_SYM  ::= "@bottom-left-corner"
BOTTOMLEFT_SYM        ::= "@bottom-left"
BOTTOMCENTER_SYM      ::= "@bottom-center"
BOTTOMRIGHT_SYM       ::= "@bottom-right"
BOTTOMRIGHTCORNER_SYM ::= "@bottom-right-corner"
LEFTTOP_SYM           ::= "@left-top"
LEFTMIDDLE_SYM        ::= "@left-middle"
LEFTBOTTOM_SYM       ::= "@right-bottom"
RIGHTTOP_SYM          ::= "@right-top"
RIGHTMIDDLE_SYM       ::= "@right-middle"
RIGHTBOTTOM_SYM       ::= "@right-bottom"

page :
       PAGE_SYM S* IDENT? pseudo_page? S*
       '{' S* [ declaration | margin ]? [ ';' S* [ declaration | margin ]? ]* '}' S*
       ;

pseudo_page :
       ':' [ "left" | "right" | "first" ]
       ;

margin :
       margin_sym S* '{' declaration [ ';' S* declaration? ]* '}' S*
       ;

margin_sym :
       TOPLEFTCORNER_SYM |
       TOPLEFT_SYM |
       TOPCENTER_SYM |
       TOPRIGHT_SYM |
       TOPRIGHTCORNER_SYM |
       BOTTOMLEFTCORNER_SYM |
       BOTTOMLEFT_SYM |
       BOTTOMCENTER_SYM |
       BOTTOMRIGHT_SYM |
       BOTTOMRIGHTCORNER_SYM |
       LEFTTOP_SYM |
       LEFTMIDDLE_SYM |
       LEFTBOTTOM_SYM |
       RIGHTTOP_SYM |
       RIGHTMIDDLE_SYM |
       RIGHTBOTTOM_SYM
       ;

The following restrictions and relaxations are made to the syntax above:

  • The value 'auto' may not be used as a page name and MUST be treated as a syntax error.

The following are examples of page selectors (declaration block intentionally left blank)

@page { ... }
@page :left { ... }
@page :right { ... }
@page LandscapeTable { ... }
@page CompanyLetterHead:first { ... } /*  identifier and pseudo page. */
@page:first { ... };

The following are examples of margin boxes where the declaration blocks are intentionally left blank.

@page {
   @top-left { ... /* document name */ }
   @bottom-center { ... /* page number */}
}
@page :left { @left-middle { ... /* page number in left margin */ }}
@page :right{ @right-middle { ... /* page number in right margins of right pages */}}

@page :left { @bottom-left-corner { ... /* left page numbers */ }}
@page :right { @bottom-right-corner { ... /* right page numbers */ }}
@page :first { @bottom-left-corner { ... /* empty footer on 1st page */ }
               @bottom-right-corner { ... /* empty footer */ } }

3.4.2. Cascading in the page context

Optionally, @page rules can have one pseudo-class (':first',':left', or 'right') and/or one named page. The specificity of @page rules are computed in an analogous manner to the computations defined in the Selectors module:

  • if an @page rule has a named page, f=1
  • if an @page rule has a ':first' pseudo-class, g=1
  • if an @page rule has a ':left' or ':right' pseudo-class, h=1

Concatenating the three numbers f-g-h gives the specificity.

Some page specificity calculation examples follow:

        @page { } /* f=0 g=0 h=0 -> specificity = 0 */
        @page :left { } /* f=0 g=0 h=1 -> specificity = 1 */
        @page :first { } /* f=0 g=1 h=0 -> specificity = 10 */
        @page artsy { } /* f=1 g=0 h=0 -> specificity = 100 */
        @page artsy:left { } /* f=1 g=0 h=1 -> specificity = 101 */
        @page artsy:first { } /* f=1 g=1 h=0 -> specificity = 110 */

Consider the following usage example:

@page {
  margin-left: 3cm;
}

@page :left {
  margin-left: 4cm;
}

Due to the higher specificity of the pseudo-class selector, the left margin on left pages will be 4 centimeters and all other pages (i.e., the right pages) will have a left margin of 3 centimeters.

In this example, the higher specificity of the green rules wins over the red rule. Therefore the first page will have blue text in the top-left margin box and green text in the top-right margin box, while subsequent pages will have red text in the margin boxes.

@page :first {
  color: green;

  @top-left {
    content: "foo";
    color: blue;
  }
  @top-right {
    content: "bar";
  }
}

@page { color: red;
  @top-center {
    content: "Page " counter(page);
    }
}

Page contexts cascade, so the following stylesheet would style pages with 25 millimeter margins and 14 point type in the margin boxes:

@page { margin: 25mm;}
@page { font-size: 14pt;}

3.5. Page Properties

The following properties can be used in the page context to style the appearance of the page box:

  • size,
  • background properties,
  • border properties,
  • margin properties, and
  • padding properties.

These properties can be used in the page context to set counters:

  • counter-reset, counter-increment,

These properties can be used in the page context to style the content of margin boxes:

  • color,
  • font properties,
  • text properties

That is, when set in the page context, the values become the initial values for the margin boxes.

These properties can be used in the margin context to style margin boxes and their content:

  • background properties,
  • border properties,
  • margin properties,
  • padding properties,
  • color,
  • font properties,
  • text properties
  • content,

The normal rules for box properties apply with the following exceptions:

  • Values in units of 'em' and 'ex' refer to the page context's font. The page context has a font associated with it either by an explicit use of the 'font-family' and 'font-size' properties or from their initial values.
  • Percentage values on the margin, padding and border properties are relative to the dimensions of the containing box (defined by the 'size' property in the page context). For left and right, the margin, border and padding percentages are relative to the width of the containing box; for top and bottom, the margin, border and padding percentages are relative to the height of the containing box.
  • The 'width' and 'height' properties do not apply to the page box (and SHOULD be treated as if they were set to 'auto').
  • The page background applies to the entire page box, including the page margins.

The page background is painted first, and covers the entire page box. A margin-box background is painted over (on top of) the page background. The root element then paints the canvas within the page area, which contains the portions of the root element formatted for a single page (including the margins of the root element).

The origin of the page background is the upper-left corner of the page area.

When a box is interrupted at the bottom of one page and continued on the top of the next, the box's margins, borders, and padding are not rendered at the bottom and top of the respective pages. Properties in other modules may modify this behavior. (At the time of writing, a property 'border-break' [CSS3BG] is under consideration.)

It is recommended that user agents with a non-printable area (that is, user agents which cannot print over the entire sheet surface) establish a default page margin via the user agent stylesheet that includes the non-printable area. It is further recommended that authors assume that the default page area will not include unprintable regions.

3.6. Left, right, and first pages

When printing double-sided documents, the page boxes on left and right pages MAY be different. This can be expressed through CSS pseudo-classes defined in the page context.

All pages are automatically classified by user agents into either the ':left' or ':right' pseudo-class. The following example creates left and right binding edges using these pseudo-classes.

@page :left {
  margin-left: 3cm;
  margin-right: 4cm;
}

@page :right {
  margin-left: 4cm;
  margin-right: 3cm;
}

If different declarations have been given for left and right pages, the user agent MUST honor these declarations even if the user agent does not transfer the page boxes to left and right sheets (e.g., a printer that only prints single-sided).

Authors MAY also specify style for the first page of a document with the ':first' pseudo-class:

@page { margin: 2cm } /* All margins set to 2cm */

@page :first {
  margin-top: 10cm /* Top margin on first page 10cm */
}

Whether the first page of a document is ':left' or ':right' depends on the major writing direction of the document and is outside the scope of this document. However, to force a ':left' or ':right' first page, authors MAY insert a page break before the first generated box (e.g., in HTML, specify this for the BODY element).

Note. Adding declarations to the ':left' or ':right' pseudo-class does not necessarily influence whether the document comes out of the printer double- or single-sided (which is outside the scope of this specification).

Note. Future versions of CSS may include other page pseudo-classes.

3.7. Content outside the page box

When formatting content in the page model, some content MAY end up outside the page box. For example, an element whose 'white-space' property has the value 'pre' MAY generate a box that is wider than the page box. Also, when boxes are positioned absolutely, they MAY end up in "inconvenient" locations. For example, images MAY be placed on the edge of the page box. Similarly when boxes use fixed or relative positioning, they MAY also end up outside of the page box.

A specification for the exact formatting of such elements lies outside the scope of this document. However, we recommend that authors and user agents observe the following general principles concerning content outside the page box:

  • User agents SHOULD avoid generating a large number of empty page boxes to honor the positioning of elements (e.g., you don't want to print 100 blank pages). Note, however, that generating a small number of empty page boxes MAY be necessary to honor the 'left' and 'right' values for 'page-break-before' and 'page-break-after'.
  • Authors SHOULD not position elements in inconvenient locations just to avoid rendering them. Instead:
    • To suppress box generation entirely, set the 'display' property to 'none'.
    • To make a box invisible, set the 'visibility' property.
  • User agents MAY handle boxes positioned outside the page box in several ways, including discarding them or creating page boxes for them at the end of the document.

4. Margin Boxes

Margin boxes can be used to create page headers and footers, which are portions of the page set aside for supplementary information such as the page number or document title. The location of page headers and footer is one of the many graphic design choices a document's author makes.

Page Header
Typically, a page header is located at the top of the page in documents with a predominately horizontal writing direction and on the side opposite the binding edge for documents with a predominately vertical writing direction. One possible design of page headers for horizontally written documents uses the 'top-left-corner', 'top-left', 'top-center', 'top-right' and 'top-right-corner' margin boxes. Another design, for vertically written documents, could use the 'right-top', 'right-middle', and 'right-bottom' margin boxes for right facing pages and 'left-top', 'left-middle', and 'left-bottom' for left facing pages. However, there are no constraints placed on the use of margin boxes for page headers, other than those expressed in the discussion of restrictions to the grammar of the page selector
Page Footer
Typically, the page footer is at the opposite end of the page from the page header. For example, the design of a horizontally written document with a page header at the top of the page could use the 'bottom-left-corner', 'bottom-left', 'bottom-center', 'bottom-right' and 'bottom-right-corner' margin boxes as the page footer. The design of a vertically written document could use the margin boxes of the binding edge of the page for the page footer. However, there are no constraints placed on the use of margin boxes for page footers, other than those expressed in the discussion of restrictions to the grammar of the page selector

Please note that the margin boxes are oriented with respect to the content and are independent of page orientation, for example the top margin boxes are above the page box in both portrait and landscape orientation.

Margin boxes are created through margin at-rules inside the page context.

4.1. At-rules for margin boxes

A margin at-rule consists of an ATKEYWORD that identifies the margin box (e.g. '@top-left') and a block of declarations (said to be in the margin context).

The following style sheet establishes a page header containing the title ("Hamlet") on the left side and the page number, preceded by "Page ", on the right side:

@page {
  size: 8.5in 11in;
  margin: 10%;

  @top-left {
    content: "Hamlet";
  }
  @top-right {
    content: "Page " counter(page);
  }
}

4.2. Maximum Dimension of margin boxes

The maximum potential width and height of each margin box is determined by establishing the containing box for the margin box in the steps shown below. There are two quantities used in the following calculations:

  • max box width, which is the sum of the width of the page's left padding area, the width of the page area, and the width of the page's right padding area. In other words, it is the distance between the left page border and the right page border. This quantity is used when calculating dimensions of the top and bottom margin boxes.
  • max box height, which is the sum of the height of the page's top padding area, the height of the page area, and the height of the page's right padding area. In other words, it is the distance between the top page border and the bottom page border. This quantity is used when calculating dimensions of the left and right margin boxes.

4.3. Dimension of margin boxes

Definitions: The "outer width" of a margin box is the sum of its used left and right margin, used left and right border, used left and right padding, and used width. The "outer height" of a margin box is the sum of its used top and bottom margin, used top and bottom border, used top and bottom padding and used height.

The following rules apply to 'top-left', 'top-center' and 'top-right' margin boxes, which are referred to as [1], [2], and [3], respectively, in the expression below.

Rules:

  • The UA chooses used values for each box's width, left and right margin, left and right border thickness, and left and right padding. It chooses them in such a way that the value of:
        left-margin[1]² + left-margin[2]² + left-margin[3]² +
    right-margin[1]² + 	right-margin[2]² + right-margin[3]²
    is as small as possible under the constraints below. ("foo[n]" stands for the used value of property foo of the n'th box and "x²" for the square of x.)
    1. The sum of the outer widths of the three boxes is equal to max box width.
    2. If the center box is not empty or if its computed width is not 'auto', then the outer widths of the other two boxes are equal to each other (i.e., the center box is centered in that case).
    3. If a box is empty and its computed width is 'auto', then the used values of its left and right padding and left and right border are all 0. (This makes such a box invisible, because, by item 5, its width is also 0.)
    4. If a box is empty and its computed width is 'auto', then the used values of its left and right padding and left and right border are all 0. (This makes such a box invisible, because, by item 5, its width is also 0.)
    5. If a box's computed width is 'auto', then: min intrinsic width <= used width <= max intrinsic width.
    6. The used values of the left box's left margin, the center box's left and right margin and the right box's right margin are their respective computed values, unless that computed value is 'auto'.
    7. The used values of the left box's right margin and the right box's left margin are their respective computed values, unless that computed value is 'auto'.
  • If the above constraints are contradictory ("over-constrained"), then constraint 7 is replaced by 7a:
    1. 7a. If the computed values of the left box's left and right margins are 'auto and not 'auto', respectively, then the used value of the right margin is its computed value. If the computed values of the right box's left and right margins are not 'auto' and 'auto', respectively, then the used value of the left margin is its computed value. This effectively means that the specified right margin of the left box is ignored if necessary, and ditto for the left margin of the right box.
  • Note that, by their definitions, margins may be negative, but widths may not.

The used values for bottom-left, bottom-center and bottom-right are established by the same rules.

The used values for left-top, left-middle and left-bottom boxes are established by the same rules, with "width" replaced by "height", "left" by "top", "right" by "bottom" and "center" by "middle".

The used values for right-top, right-middle and right-bottom boxes are established by the same rules as for left-top, left-middle and left-bottom.

4.4. Margin boxes and default values

Margin boxes have an initial value of zero for padding, border and margin. The default height of top boxes is the value of the page box's top margin. The default height of the bottom boxes is the value of the page box's bottom margin.

The initial value for 'content' is 'none'. The initial 'width' and 'height' of margin boxes is 'auto'. The initial value of text-align and vertical-align is defined below:

Table 2. Initial values for Margin Boxes
Margin box | 'text-align' | 'vertical-align'
top-left-corner | right | middle
top-left | left | middle
top-center | center | middle
top-right | right | middle
top-right-corner | left | middle
left-top | center | top
left-middle | center | middle
left-bottom | center | bottom
right-top | center | top
right-middle | center | middle
right-bottom | center | bottom
bottom-left-corner | right | middle
bottom-left | left | middle
bottom-center | center | middle
bottom-right | right | middle
bottom-right-corner | left | middle

4.4.1. Margin box examples

The following is a collection of examples of margin box usage.

Here is an example of a page with only a top-left header:

@page {
  @top-left { content: "Header in Left Cell (top-left)" }
}

Because there are no contents defined for the top-center or the top-right margin boxes, the extent of the top-left margin box is allowed to cross the center of the page box.

Header Example 1

The following is an example of a page with a centered header:

@page {
  @top-center { content: "Header in Center Cell (top-center)" }
}

Header Example 2

The following is an example of a page with a single header in the top-right margin box:

@page {
  @top-right { content: "Header in Right Cell (top-right)" }
}

Because the content of the center cell is empty, the extent of the top-right margin box is allowed to cross the center of the page box.

Header Example 3

The following is an example of a page with a top-center and a top-left header:

@page {
  @top-left { content: "Left Cell (top-left)" }
  @top-center { content: "Header in Center Cell (top-center)" }
}

Header Example 4

The following is an example of a page with a top-center and a top-right header:

@page {
  @top-center { content: "Header in Center Cell (top-center)" }
  @top-right { content: "Right Cell (top-right)" }
}

Header Example 5

The following is an example of a page with top-left and top-right headers:

@page {
  @top-left { content: "Header in top-left with approx. "
                     "twice as many words as right cell." }
  @top-right { content: "Right cell (top-right)" }
}

Because there are no center cell contents, the extent of the top-left is allowed to cross the center of the page box. As the intrinsic width of the top-left contents is approximately twice the intrinsic width of that of the top-right, the top-left margin box is approximately twice as wide as the top-right margin box.

Header Example 6

4.5. Populating margin boxes

A margin box is instantiated if a margin context is established and one of the following conditions holds:

  • The computed value of 'content' is not 'none'.
  • The properties 'width' and 'height' are set in the margin context.

This example style sheet could be used to create a centered header with the current chapter name:

body {counter-reset: chapter;}
div.chapter {counter-increment: chapter;}
@page {
  margin: 10%;
  @top-center { content: "Chapter" counter(chapter) }
}

Note that a counter value could be updated many times on a given page. The value of the counter at the beginning of page processing MUST be used by default.

5. Page Breaks

The following sections explain page formatting in CSS3 paged media. Five properties indicate where the user agent MAY or SHOULD break pages, and on what page (left or right) the subsequent content SHOULD resume. Each page break ends layout in the current page box and causes remaining pieces of the document tree to be laid out in a new page box.

5.1. Break before/after elements: 'page-break-before', 'page-break-after', 'page-break-inside'

Name: | page-break-before
Value: | auto | always | avoid | left | right
Initial: | auto
Applies to: | block-level elements
Inherited: | no
Percentages: | N/A
Media: | paged
Computed value: | specified value
Name: | page-break-after
Value: | auto | always | avoid | left | right
Initial: | auto
Applies to: | block-level elements
Inherited: | no
Percentages: | N/A
Media: | paged
Computed value: | specified value
Name: | page-break-inside
Value: | auto | avoid
Initial: | auto
Applies to: | block-level elements
Inherited: | yes
Percentages: | N/A
Media: | paged
Computed value: | specified value

Values for these properties have the following meanings:

auto
Neither force nor forbid a page break before (after, inside) the generated box.
always
Always force a page break before (after) the generated box.
avoid
Avoid a page break before (after, inside) the generated box.
left
Force one or two page breaks before (after) the generated box so that the next page is formatted as a left page.
right
Force one or two page breaks before (after) the generated box so that the next page is formatted as a right page.

A potential page break location is typically under the influence of the parent element's 'page-break-inside' property, the 'page-break-after' property of the preceding element, and the 'page-break-before' property of the following element. When these properties have values other than 'auto', the values 'always', 'left', and 'right' take precedence over 'avoid'. See the section on allowed page breaks for the exact rules on how these properties MAY force or suppress a page break.

5.2. Using named pages: 'page'

Name: | page
Value: | auto | <identifier>
Initial: | auto
Applies to: | block-level elements
Inherited: | yes
Percentages: | N/A
Media: | paged
Computed value: | specified value

The 'page' property can be used to specify a particular type of page where an element SHOULD be displayed.

This example will put all tables on a right-hand side landscape page (named "rotated"):

@page rotated { size: landscape }
table { page: rotated; page-break-before: right }

The 'page' property works as follows: If a block box with inline content has a 'page' property that is different from the preceding block box with inline content, then one or two page breaks are inserted between them, and the boxes after the break are rendered on a page box of the named type. See "Forced page breaks" below.

In this example, the two tables are rendered on landscape pages (indeed, on the same page, if they fit). The page type "narrow" is used for the <p> after the second table, as the page properties for the table element are no longer in effect:

@page narrow { size: 9cm 18cm }
@page rotated { size: landscape }
div { page: narrow }
table { page: rotated }
with this document:
<div>
<table>...</table>
<table>...</table>
<p>This text is rendered on a 'narrow' page</p>
</div>

5.3. Breaks inside elements: 'orphans', 'widows'

Name: | orphans
Value: | <integer>
Initial: | 2
Applies to: | block-level elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value
Name: | widows
Value: | <integer>
Initial: | 2
Applies to: | block-level elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value

The 'orphans' property specifies the minimum number of lines of a paragraph that MUST be left at the bottom of a page. The 'widows' property specifies the minimum number of lines of a paragraph that MUST be left at the top of a page. Examples of how they are used to control page breaks are given below.

If a paragraph contains fewer lines than the value of 'widows' or 'orphans', the rule is relaxed.

5.4. Allowed page breaks

In the normal flow, page breaks may occur at the following places:

  1. In the vertical margin between block boxes (or rows in a table). When a page break occurs here, the computed values of the relevant 'margin-top' and 'margin-bottom' properties are set to '0'.
  2. Between line boxes inside a block box.

These breaks are subject to the following rules:

  • Rule A: Breaking at (1) is allowed only if the 'page-break-after' and 'page-break-before' properties of all the elements generating boxes that meet at this margin allow it, which is when at least one of them has the value 'always', 'left', or 'right', or when all of them are 'auto'.
  • Rule B: However, if all of them are 'auto' and the nearest common ancestor of all the elements has a 'page-break-inside' value of 'avoid', then breaking here is not allowed.
  • Rule C: Breaking at (2) is allowed only if the number of line boxes between the break and the start of the enclosing block box is the value of 'orphans' or more, and the number of line boxes between the break and the end of the box is the value of 'widows' or more.
  • Rule D: In addition, breaking at (2) is allowed only if the 'page-break-inside' property is 'auto'.

If the above doesn't provide enough break points to keep content from overflowing the page boxes, then rules B and D are dropped in order to find additional breakpoints.

If that still does not lead to sufficient break points, rules A and C are dropped as well, to find still more break points.

5.5. Forced page breaks

A page break MUST occur at (1) if, among the 'page-break-after' and 'page-break-before' properties of all the elements generating boxes that meet at this margin, there is at least one with the value 'always', 'left', or 'right'.

When multiple 'page-break-before' and/or 'page-break-after; properties with values of "always", "left" or "right" apply at a margin, only one of them should generate page breaks. That is, no content-empty pages are generated by page-break properties, except for at most one content-empty page as may be required by :right and :left values to position ensuing content on a right- or left-facing page.

A page break MUST also occur at (1) if the last line box above this margin and the first one below it do not have the same value for 'page'.

5.6. "Best" page breaks

CSS3 does not define which of a set of allowed page breaks MUST be used; except as defined earlier in the section, CSS3 does not forbid a user agent to break at every possible break point, or to not break at all. But CSS3 does recommend that user agents observe the following heuristics (while recognizing that they are sometimes contradictory):

  • Break as few times as possible.
  • Make all pages that don't end with a forced break appear to have about the same height.
  • Avoid breaking inside a block that has a border.
  • Avoid breaking inside a table.
  • Avoid breaking inside a floated element.

Suppose, for example, that the style sheet contains 'orphans : 4', 'widows : 2', and there are 20 lines (line boxes) available at the bottom of the current page:

  • If a paragraph at the end of the current page contains 20 lines or fewer, it SHOULD be placed on the current page.
  • If the paragraph contains 21 or 22 lines, the second part of the paragraph MUST not violate the 'widows' constraint, and so the second part MUST contain exactly two lines.
  • If the paragraph contains 23 lines or more, the first part SHOULD contain 20 lines and the second part the remaining lines.

Now suppose that 'orphans' is '10', 'widows' is '20', and there are 8 lines available at the bottom of the current page:

  • If a paragraph at the end of the current page contains 8 lines or fewer, it SHOULD be placed on the current page.
  • If the paragraph contains 9 lines or more, it cannot be split (that would violate the orphan constraint), so it SHOULD move as a block to the next page.

6. Page-based Extensions to Counters

6.1. Page-based counters

Counters apply to page contexts defined by means of the '@page' rule. This is useful for maintaining a page count.

The following rules result in the placement of the current page number in the middle of the outside margin of each page.

@page {
  margin: 10%;
  counter-increment: page;

  @top-center {
    font-family: sans-serif;
    font-weight: bold;
    font-size: 2em;
    content: counter(page);
  }
}

7. Orienting an Image on the Page

Images from camera phones, digital cameras or scanners may be encoded sideways. For example, the first row of image data may represent the leftmost or rightmost column of image pixels. Furthermore, often such devices have limited resources, and do not have the capability to rotate the image into an upright orientation. However, this type of device may have internal knowledge or can accept input from its user on the rotational correction to perform.

The image-orientation property provides a way to specify a rotation to be applied to an image. This facility is not intended to specify other image transformations such as flipping the image in the horizontal or vertical direction. Also, this facility is not needed to correctly orient an image when printing in landscape versus portrait orientation.

Name: | image-orientation
Value: | auto | <angle>
Initial: | auto
Applies to: | images
Inherited: | N/A
Percentages: | N/A
Media: | paged
Computed value: | specified value modulo full circle value

'image-orientation' specifies a rotation in the right or clockwise direction that a user agent applies to an image. In terms of the order of transformations, the image is first rotated, then sized, then positioned. Thus height and width properties apply to the rotated rather than the original image dimensions.

Two values for the 'image-orientation' property apply to an image:

auto
The image will be set to the orientation of the page. That is, for a pixelated image consisting of rows and columns of pixels, a row is displayed across the width of the display surface and a column along the height.
<angle>
A positive value rotates the image to the right (in a clockwise direction) by the given number of degrees. Negative values rotate to the left or in a counter-clockwise direction. Specified values outside the range of ]-360, 360[ degrees are moduloed by 360 to produce a computed value within that range. User agents MUST support values which compute to 0, 90, 180, and 270 degrees. Support for other values is optional.
The following examples rotate the image in four major orientations:
img.original   { image-orientation: auto  }
img.zero       { image-orientation: 0 }
img.ninety     { image-orientation: 90deg }
img.tilt       { image-orientation: -1deg }
...
<img class="ninety" src=... />

8. The 'fit' and 'fit-position' Properties

Name: | fit
Value: | fill | hidden | meet | slice
Initial: | fill
Applies to: | replaced elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value

Name: | fit-position
Value: | [ [<percentage> | <length> ]{1,2} | [ [top | center | bottom] || [left | center | right] ] ] | auto
Initial: | 0% 0%
Applies to: | replaced elements
Inherited: | yes
Percentages: | refer to width and height of box itself
Media: | visual
Computed value: | specified value

The 'fit' property gives a hint for how to scale a replaced element if neither its 'width' nor its 'height' property is 'auto'. Not all replaced objects can be scaled, but images typically can.

fill
Scale the object's height and width independently so that the content just touches all edges of the containing box.
hidden
Do not scale the object.
meet
Make the object as large as possible with its width <= 'width' and height <= 'height', while preserving its aspect ratio. Position the object as for the 'hidden' value.
slice
Make the object as small as possible with its width >= 'width' and height >= 'height', while preserving its aspect ratio. Position the object as for the 'hidden' value.

'Hidden' is not really an intuitive name, 'none' might be better. But SMIL already uses 'hidden'...

See the 'overflow' property for how to render parts of the object that extend beyond the edges of the box.

The keywords are intended to convey the visual effect in the case that 'overflow' is 'hidden', which is expected to be the most common case.

Illustration of the four values

An example showing how each of the four values of 'fit' causes the object (gray rectangle) to be scaled to fit the given box (red dotted outline).

The 'fit-position' determines the alignment of the object inside the box. The values have the same meaning as the values on 'background-position', with the addition of the value 'auto', specifically:

<percentage> <percentage>
With a value pair of '0% 0%', the upper left corner of the image is aligned with the upper left corner of the box's padding edge. A value pair of '100% 100%' places the lower right corner of the image in the lower right corner of padding area. With a value pair of '14% 84%', the point 14% across and 84% down the image is to be placed at the point 14% across and 84% down the padding area.
<length> <length>
With a value pair of '2cm 2cm', the upper left corner of the image is placed 2cm to the right and 2cm below the upper left corner of the padding area.
'top left', 'left top'
Same as '0% 0%'.
'top', 'top center', 'center top'
Same as '50% 0%'.
'right top', 'top right'
Same as '100% 0%'.
'left', 'left center', 'center left'
Same as '0% 50%'.
'center', 'center center'
Same as '50% 50%'.
'right', 'right center', 'center right'
Same as '100% 50%'.
'bottom left', 'left bottom'
Same as '0% 100%'.
'bottom', 'bottom center', 'center bottom'
Same as '50% 100%'.
'bottom right', 'right bottom'
Same as '100% 100%'.
auto
Put the object's top left corner in the top left corner of the box. Properties in other modules may modify this behavior. (At the time of writing, a property 'writing-mode' is under consideration.)

The computed value is the same as the specified value, i.e., the keywords are not replaced by percentages and the percentages are not replaced by something else. (This is an exception to the general rule that percentages are computed to some other value before being inherited.)

Note: areas of the box not covered by the replaced element will show the element's 'background'.

Note: the 'fit' property has the same meaning as the fit attribute in [SMIL10], except that the value 'scroll' is not available, because the 'overflow' property can be used instead.

References

Normative References

[CSS21]
Bert Bos; et al. Cascading Style Sheets, level 2 revision 1. 11 April 2006. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2006/WD-CSS21-20060411
[PWGMSN]
Ron Bergman; Tom Hastings. Media Standardized Names. 26 February 2002. IEEE ISTO Printer Working Group 5101.1-2002. URL: ftp://ftp.pwg.org/pub/pwg/candidates/cs-pwgmsn10-20020226-5101.1.pdf
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt

Informative References

[CSS3BG]
Tim Boland; Bert Bos. CSS3 Backgrounds and Borders Module. 16 February 2005. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2005/WD-css3-background-20050216
[MEDIAQ]
Håkon Wium Lie; Tantek Çelik; Daniel Glazman. Media Queries. 8 July 2002. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2002/CR-css3-mediaqueries-20020708
[SMIL10]
Philipp Hoschka (ed). Synchronized Multimedia Integration Language (SMIL) 1.0 Specification. 15 June 1998. W3C Recommendation. URL: http://www.w3.org/TR/1998/REC-smil-19980615


CSS3 module- Presentation Levels

CSS3 module: Presentation Levels

W3C Working Draft 13 August 2003

This version:
http://www.w3.org/TR/2003/WD-css3-preslev-20030813
Latest version:
http://www.w3.org/TR/css3-preslev
Editors:
Ian Hickson <ian @hixie.ch>
Håkon Wium Lie <howcome @opera.com>

Copyright © 2003 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.

Abstract

Presentation levels are integer values attached to elements in a document. Elements that are below, at, or above a certain threshold can be styled differently. This feature has two compelling use cases. First, slide presentations with transition effects can be described. For example, list items can be progressively revealed by sliding in from the side. Second, outline views of documents, where only the headings to a certain level are visible, can be generated.

Status of This Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document is a working draft of the CSS working group, which is part of the style activity (see summary).

The working group believes this draft describes useful functionality for presenting web documents. Comments on, and discussions of this draft can be sent on the (archived) public mailing list www-style@w3.org (see instructions). W3C Members can also send comments directly to the CSS working group.

It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress". Its publication does not imply endorsement by the W3C membership or the CSS Working Group (members only).

Patent disclosures relevant to CSS may be found on the Working Group's public patent disclosure page.

Table of contents

  • 1. The model
  • 2. The 'presentation-level' property
  • 3. Example 1: progressively revealing list items
  • 4. Example 2: presenting outline views of a document
  • 5. Presentation levels and the DOM

1. The model

Content reuse has been one of the main motivations for the development of style sheets. By associating documents with different style sheets, the same content can be presented in different ways. The introduction of presentation levels in CSS adds functionality which is very useful in two particular settings. First, slide presentations with transition effects can be described. For example, list items can be progressively revealed by sliding in from the side. Second, outline views of documents, where only the headings to a certain level are visible, can be generated.

The model behind presentation levels is simple. Each element in the document is assigned an integer value which is referred to as the "element's presentation level" (EPL). The EPL can be set explicitly in a style sheet or calculated automatically based on the element's position in the document structure: it is specified by the computed value of the 'presentation-level' property. The User Agent maintains another integer value which is called the User Agent Presentation Value (UAPL). The UAPL starts at a UA-defined value, typically 0.

All elements are in one of three presentation pseudo-classes: 'below-level', 'at-level', and 'above-level'. These pseudo-classes refer to whether the element's EPL was below, at, or above the UAPL the last time the UAPL changed. When an element's state is evaluated, the EPL is compared to the UAPL and pseudo-classes are assigned as follows: If the EPL is equal to 0, the element is always in the below-level state. If the EPL is lower than the UAPL value, it is set to the 'below-level' state, if the EPL is exactly that value it is set to 'at-level', and if the EPL is greater than that value it is set to 'above-level'.

Here is an example of a style sheets using the presentation pseudo-classes:

  :below-level { color: black }
  :at-level { color: red }
  :above-level { color: silver }

This proposal does not describe the user interface of presentation levels. The user agent will need to provide a user interface for setting the UAPL. For example, in projection mode, a user agent may increase the UAPL every time the user hits the space bar. When the user moves to another page (for example by following a hyperlink), the user agent may set the UAPL to be the same as presentation level of the first element on the page. In outline mode, the user agent may provide a vertical slider on the side to increase/decrease the UAPL.

2. The 'presentation-level' property

Name: | presentation-level
Value: | <integer> | same | increment
Initial: | 0
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | all
Computed value: | integer
POWERED BY HeroNote

This property sets the element's presentation level (EPL). The values have the following meanings:

  • An integer value sets the presentation level explicitly.
  • A value of 'increment' computes to a value one more than the previous (in document order) element's presentation level.
  • A value of 'same' computes to the same value as the previous element's (in document order) presentation level. For the root element, 'same' computes to zero.

3. Example 1: progressively revealing list items

Here is an example of how presentation levels can be used to progressively reveal list items while high-lighting the current one.

                                                   EPL value
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>                                             0
<STYLE>                                            0
  html { color: black; background: white }
  @media projection {
    h1 { page-break-before: always }
    li { presentation-level: increment }
    :below-level { color: black }
    :at-level { color: red }
    :above-level { color: silver }
  }
</STYLE>
<BODY>                                             0
<H1>Strategies</H1>                                0
<H2>Our strategy</H2>                              0
<UL>                                               0
  <LI>divide                                       1
  <LI>conquer                                      2
  <P>(in that order)                               2
</UL>
<H2>Their strategy</H2>                            0
<UL>                                               0
  <LI>obfuscate                                    1
  <LI>propagate                                    2
</UL>

In the example above, the LI elements' EPL value is increased with one compared to the previous element. The other elements' EPL value is the same as the previous element due to the initial 'same' value of the 'presentation-level' property.

4. Example 2: presenting outline views of a document

Here is an example of how presentation levels can be used to present outline views of a document:

                                                   EPL value
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>                                             0
<STYLE>
   h1 { presentation-level: 0; }
   h2 { presentation-level: 1; }
   h3 { presentation-level: 2; }
   body * { presentation-level: 3; }
   :above-level { display: none; }
</STYLE>
<BODY>                                             0
<H1>Strategies</H1>                                3
<H2>Our strategy</H2>                              2
<UL>                                               0
<LI>divide                                         0
<LI>conquer                                        0
<P>(in that order)                                 0
</UL>
<H2>Their strategy</H2>                            2
<UL>                                               0
<LI>obfuscate                                      0
<LI>propagate                                      0
</UL>

5. Presentation levels and the DOM

An element's state is first evaluated when it is created. When the UAPL is changed, all elements in the document have their state reevaluated. A CSSNowBelowLevel event is then sent to all elements that changed to the 'below-level' state, a CSSNowAtLevel event is then sent to all elements that changed to the 'at-level' state, and a CSSNowAboveLevel event is then sent to all elements that changed to the 'above-level' state. Changing an element's 'presentation-level' property, e.g. through the DOM or using a dynamic pseudo-class, does not cause the element's state to be immediately reevaluated.

These events have the following characteristics:

  • Bubbles: Yes
  • Cancelable: No
  • Context Info: detail (the UAPL)

SMIL can be used with this event to declaratively key animations from user requests, based on the 'presentation-index' property.

The events are defined as:

   interface CSSNowBelowLevel : UIEvent { }
   interface CSSNowAtLevel : UIEvent { }
   interface CSSNowAboveLevel : UIEvent { }

These three fragments together will cause a document to have three user-triggered list items, which will scroll in one at a time each time the user hits the space bar (or whatever mechanism the UA uses), with the current item colored white and the past items colored gray.

Markup:

    <ol>
     <li> The Separation of Style and Structure </li>
     <li> Declarative User Interaction </li>
     <li> Potential for Animation </li>
    </ol>

Stylesheet:

     ol { overflow: hidden; }
     li { presentation-level: increment; margin-left: 100%; }
     li:at-level { color: white; }
     li:above-level { color: silver; }

Script:

    // When the element is shown, scroll it in from the right
    // by animating the margin-left property from 100% to 0%
    document.documentElement.addEventListener('CSSNowAtLevel', handler, false);

    function handler(event) {
      // animateFloat is a (fictional) library routine which takes
      // five arguments:
      //  a CSSValue to animate
      //  the start value
      //  the end value
      //  the time over which to animate the property, in milliseconds
      //  the units to animate it with
      // it returns straight away and performs the animation in the
      // background.
      animateFloat(document.getOverrideStyle(event.target,
                                  null).getPropertyCSSValue('margin-left'),
                   100, 0, 1000, CSS_PERCENTAGE);
    }


CSS3 module- Syntax

CSS3 module: Syntax

W3C Working Draft 13 August 2003

This version:
http://www.w3.org/TR/2003/WD-css3-syntax-20030813
Latest version:
http://www.w3.org/TR/css3-syntax
Previous version:
none
Editor:
L. David Baron, <dbaron@dbaron.org>
Additional Contributors:
Original CSS2 Authors
Bert Bos (W3C), <bert@w3.org>
Peter Linss (Netscape)

Copyright © 2003 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.

Abstract

This CSS3 module describes the basic structure of CSS style sheets, some of the details of the syntax, and the rules for parsing CSS style sheets. It also describes (in some cases, informatively) how stylesheets can be linked to documents and how those links can be media-dependent. Additional details of the syntax of some parts of CSS described in other modules will be described in those modules. The selectors module has a grammar for selectors. Modules that define properties give the grammar for the values of those properties, in a format described in this document.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/. The latest revision can also be found by following the "Latest Version" link above.

This document is a draft of one of the modules of CSS Level 3 (CSS3). Some parts of the document are derived from the CSS Level 1 and CSS Level 2 recommendations, and those parts are thus relatively stable. However, it is otherwise an early draft, and considerable revision is expected in later drafts, especially in formalization of error handling behavior, the conformance requirements for partial implementations (given the modularization of CSS3), and integration with other CSS3 modules.

This document is a working draft of the CSS working group which is part of the style activity (see summary).

The working group would like to receive feedback: discussion takes place on the (archived) public mailing list www-style@w3.org (see instructions). W3C Members can also send comments directly to the CSS working group.

This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress. Its publication does not imply endorsement by the W3C membership or the CSS & FP Working Group (members only).

Patent disclosures relevant to CSS may be found on the Working Group's public patent disclosure page.

This document may be available in translations in the future. The English version of this specification is the only normative version.

Table of contents

  • 1. Dependencies on other modules
  • 2. Introduction
  • 3. CSS style sheet representation
    • 3.1. Referring to characters not represented in a character encoding
    • 3.2. The text/css content type
  • 4. General syntax of CSS
    • 4.1. Characters and case
    • 4.2. Tokenization
    • 4.3. Grammar
      • 4.3.1. Principles of CSS error handling
      • 4.3.2. Style sheets
    • 4.4. Keywords
    • 4.5. Statements
    • 4.6. At-rules
    • 4.7. Blocks
    • 4.8. Rule sets, declaration blocks, and selectors
    • 4.9. Declarations and properties
    • 4.10. Comments
  • 5. Rules for handling parsing errors or unsupported features
    • 5.1. Partial implementations
  • 6. Vendor-specific extensions
    • 6.1. Historical notes
  • 7. Associating style sheets with documents
    • 7.1. Media types
      • 7.1.1. Introduction to media types
      • 7.1.2. Specifying media-dependent style sheets
      • 7.1.3. The @media rule
      • 7.1.4. Recognized media types
      • 7.1.5. Extensions to media types
    • 7.2. User-agent style sheets
    • 7.3. User style sheets
    • 7.4. Author style sheets
    • 7.5. Style sheets including other style sheets: the @import rule
  • 8. Defining namespaces: the @namespace rule
  • 9. Conformance
    • 9.1. Definitions
    • 9.2. User agent conformance
      • 9.2.1. Error conditions
    • 9.3. Style sheet conformance
    • 9.4. Authoring tool conformance
  • 10. Format of property definitions in other modules
    • 10.1. Value
      • 10.1.1. initial and inherit values
    • 10.2. Initial
    • 10.3. Applies to
    • 10.4. Inherited
    • 10.5. Computed value
    • 10.6. Percentage values
    • 10.7. Media groups
    • 10.8. Shorthand properties
  • 11. Appendix: Second grammar
    • 11.1. Grammar
    • 11.2. Lexical scanner
  • Changes from CSS2
  • Acknowledgments
  • References
    • Normative references
    • Other references
  • Index

1. Dependencies on other modules

This CSS3 module depends on the following other CSS3 modules:

  • Selectors [SELECT]
  • CSS3 module: Values & Units [CSS3VAL]
  • CSS3 module: Cascading & Inheritance [CSS3CASCADE]

It has non-normative (informative) references to the following other CSS3 modules:

  • Media queries [MEDIAQ]
  • Generated Content [CSS3GENCON]

2. Introduction

This specification describes the basic syntax of CSS3 and the syntax conventions used in the property definitions spread through the CSS3 modules. The syntax of CSS3 has some error-handling requirements for forward-compatibility, but much of the error-handling behavior depends on the user agent.

3. CSS style sheet representation

A CSS style sheet is a sequence of characters from the Universal Character Set (see [ISO10646]). For transmission and storage, these characters must be encoded by a character encoding that supports the set of characters available in US-ASCII (e.g., ISO-8859-x, Shift_JIS, etc.). A byte order mark (BOM), as described in section 2.7 of [UNICODE310], that begins the sequence of characters should not be considered, for purposes of applying the grammar below, as a part of the style sheet. For a good introduction to character sets and character encodings, please consult the HTML 4.0 specification ([HTML40], chapter 5). See also the XML 1.0 specification ([XML10], sections 2.2 and 4.3.3).

When a style sheet is embedded in another document, such as in the STYLE element or "style" attribute of HTML, the style sheet shares the character encoding of the whole document.

When a style sheet resides in a separate file, user agents must observe the following priorities when determining a style sheet's character encoding (from highest priority to lowest):

  1. A character encoding specified by a higher level protocol (e.g., the "charset" parameter to the MIME type specified in an HTTP "Content-Type" field). (The HTTP protocol ([HTTP11], section 3.7.1) mentions ISO-8859-1 as a default character encoding when the "charset" parameter is absent from the "Content-Type" header field. In practice, this recommendation has proved useless because some servers don't allow a "charset" parameter to be sent, and others may not be configured to send the parameter. Therefore, user agents must not assume any default value for the "charset" parameter, but must instead look for the @charset rule.)
  2. The @charset at-rule.
  3. Assume that the style sheet is UTF-8.

Since the third point differs from CSS1 and CSS2, authors should not rely on user agents to assume that style sheets without encoding information are UTF-8 encoded. Authors should specify the encoding using one of the first two methods.

At most one @charset rule may appear in an external style sheet - it must not appear in an embedded style sheet - and it must appear at the very start of the style sheet, not preceded by any characters (except for the optional Byte Order Mark described above). After "@charset", authors specify the name of a character encoding. The name must be a charset name as described in the IANA registry (See [RFC2978]. Also, see [CHARSETS] for a complete list of charsets). For example:

@charset "ISO-8859-1";

This specification does not mandate which character encodings a user agent must support. [Should we require a certain minimal set, such as UTF-8 and UCS2?]

Note that reliance on the @charset construct theoretically poses a problem since there is no a priori information on how it is encoded. In practice, however, the encodings in wide use on the Internet are either based on ASCII, UTF-16, UCS-4, or (rarely) on EBCDIC. This means that in general, the initial byte values of a style sheet enable a user agent to detect the encoding family reliably, which provides enough information to decode the @charset rule, which in turn determines the exact character encoding.

[Should this specification describe how to handle encoding errors? Can a user agent ignore the @charset rule if it's wrong? What if the user agent does not support the encoding used? Should this specification describe how to handle a @charset rule that specifies a character encoding that is incompatible with the family of encodings used to decode the @charset rule (and BOM) itself?]

3.1. Referring to characters not represented in a character encoding

A style sheet may have to refer to characters that cannot be represented in the current character encoding. These characters must be written as escaped references to ISO 10646 characters. These escapes serve the same purpose as numeric character references in HTML or XML documents (see [HTML40], chapters 5 and 25).

The character escape mechanism should be used when only a few characters must be represented this way. If most of a style sheet requires escaping, authors should encode it with a more appropriate encoding (e.g., if the style sheet contains a lot of Greek characters, authors might use "ISO-8859-7" or "UTF-8").

Intermediate processors using a different character encoding may translate these escaped sequences into byte sequences of that encoding. Intermediate processors must not, on the other hand, alter escape sequences that cancel the special meaning of an ASCII character.

Conforming user agents must correctly map to Unicode all characters in any character encodings that they recognize (or they must behave as if they did).

For example, a style sheet transmitted as ISO-8859-1 (Latin-1) cannot contain Greek letters directly: "??????" (Greek: "kouros") has to be written as "\3BA\3BF\3C5\3C1\3BF\3C2".

Note. In HTML 4.0, numeric character references are interpreted in "style" attribute values but not in the content of the STYLE element. Because of this asymmetry, we recommend that authors use the CSS character escape mechanism rather than numeric character references for both the "style" attribute and the STYLE element. For example, we recommend:

<span style="voice-family: D\FC rst">...</span>

rather than:

<span style="voice-family: D&#252;rst">...</span>

3.2. The text/css content type

CSS style sheets that exist in separate files are sent over the Internet as a sequence of bytes accompanied by encoding information. The structure of the transmission, termed a message entity, is defined by MIME and HTTP 1.1 (see [RFC2045] and [HTTP11]). A message entity with a content type of "text/css" represents an independent CSS style sheet. The "text/css" content type has been registered by RFC 2318 ([RFC2318]).

4. General syntax of CSS

This section describes a grammar (and forward-compatible parsing rules) common to any version of CSS (including CSS3). Future versions of CSS will adhere to this core syntax, although they may add additional syntactic constraints.

See the section on characters and case for information on case-sensitivity.

These descriptions are normative.

4.1. Characters and case

The following rules always hold:

  • All CSS style sheets are case-insensitive, except for parts that are not under the control of CSS. For example, the case-sensitivity of values of the HTML attributes "id" and "class", of font names, and of URIs lies outside the scope of this specification. Note in particular that element names are case-insensitive in HTML, but case-sensitive in XML.

  • In CSS3, identifiers (including element names, classes, and IDs in selectors (see [SELECT] [or is this still true])) can contain only the characters [A-Za-z0-9] and ISO 10646 characters 161 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit or a hyphen followed by a digit. They can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F". (See [UNICODE310] and [ISO10646].)

  • In CSS3, a backslash (\) character indicates three types of character escapes.

    First, inside a string (see [CSS3VAL]), a backslash followed by a newline is ignored (i.e., the string is deemed not to contain either the backslash or the newline).

    Second, it cancels the meaning of special CSS characters. Any character (except a hexadecimal digit) can be escaped with a backslash to remove its special meaning. For example, "\"" is a string consisting of one double quote. Style sheet preprocessors must not remove these backslashes from a style sheet since that would change the style sheet's meaning.

    Third, backslash escapes allow authors to refer to characters they can't easily put in a style sheet. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number. If a digit or letter follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

    1. with a space (or other whitespace character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (13/10) as a single whitespace character.
    2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

    In fact, these two methods may be combined. Only one whitespace character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must itself either be escaped or doubled.

  • Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).

4.2. Tokenization

[This needs to be integrated with the selectors module. How should that be done?]

All levels of CSS - level 1, level 2, level 3, and any future levels - use the same core syntax. This allows UAs to parse (though not completely understand) style sheets written in levels of CSS that didn't exist at the time the UAs were created. Designers can use this feature to create style sheets that work with older user agents, while also exercising the possibilities of the latest levels of CSS.

At the lexical level, CSS style sheets consist of a sequence of tokens. Hexadecimal codes (e.g., #x20) refer to ISO 10646 ([ISO10646]). In case of multiple matches, the longest match determines the token.

The following productions are parts of tokens:

[We need something to allow signs on integers. Do we need to go as far as css3-selectors?]

ident | ::= | '-'? nmstart nmchar*
name | ::= | nmchar+
nmstart | ::= | [a-zA-Z] | '_' | nonascii | escape
nonascii | ::= | [#x80-#xD7FF#xE000-#xFFFD#x10000-#x10FFFF]
unicode | ::= | '\' [0-9a-fA-F]{1,6} wc?
escape | ::= | unicode | '\' [#x20-#x7E#x80-#xD7FF#xE000-#xFFFD#x10000-#x10FFFF]
nmchar | ::= | [a-zA-Z0-9] | '-' | '_' | nonascii | escape
num | ::= | [0-9]+ | [0-9]* '.' [0-9]+
string | ::= | '"' (stringchar | "'")* '"' | "'" (stringchar | '"')* "'"
stringchar | ::= | urlchar | #x20 | '\' nl
urlchar | ::= | [#x9#x21#x23-#x26#x27-#x7E] | nonascii | escape
nl | ::= | #xA | #xD #xA | #xD | #xC
w | ::= | wc*
wc | ::= | #x9 | #xA | #xC | #xD | #x20

The following productions are the complete list of tokens in CSS3:

IDENT | ::= | ident
ATKEYWORD | ::= | '@' ident
STRING | ::= | string
HASH | ::= | '#' name
NUMBER | ::= | num
PERCENTAGE | ::= | num '%'
DIMENSION | ::= | num ident
URI | ::= | "url(" w (string | urlchar* ) w ")"
UNICODE-RANGE | ::= | "U+" [0-9A-F?]{1,6} ('-' [0-9A-F]{1,6})?
CDO | ::= | "<!--"
CDC | ::= | "-->"
S | ::= | wc+
COMMENT | ::= | "/*" [^*]* '*'+ ([^/] [^*]* '*'+)* "/"
FUNCTION | ::= | ident '('
INCLUDES | ::= | "~="
DASHMATCH | ::= | "|="
PREFIXMATCH | ::= | "^="
SUFFIXMATCH | ::= | "$="
SUBSTRINGMATCH | ::= | "*="
CHAR | ::= | any other character not matched by the above rules, except for " or '
BOM | ::= | #xFEFF

Since any single character other than ' or " that cannot be part of a larger token is a single character token, there cannot be errors in tokenization other than the inability to tokenize an unmatched quotation mark. If at some point it is not possible to continue tokenizing an incoming style sheet, the remainder of the style sheet should be ignored and only the largest initial segment of the style sheet that can be tokenized according to the above rules (that is, the entire style sheet except for the part from the unmatched (single or double) quotation mark to the end) should be used to form the sequence of tokens to be parsed according to the grammar.

[This isn't exactly right. Since the string token can't contain newlines that aren't escaped by backslashes, an untokenizable sequence can occur in the middle of a file. Would it be better to change things so that unmatched quotation marks become single-character tokens and all character streams are tokenizable?]

4.3. Grammar

4.3.1. Principles of CSS error handling

All levels of CSS, starting from CSS1, have required that user agents ignore certain types of invalid style sheets in well-defined ways. This allows forward-compatibility, since it allows future extensions to CSS within basic grammatical constraints that will be ignored in well-defined ways by user agents implementing earlier versions of CSS.

Handling of CSS that is not valid CSS3 but is valid according to the forward-compatible syntax requires first determining the beginning and end of the part that is invalid and then handling that part in a specified way. The latter is described in the rules for handling parsing errors. The mechanism for the former is described within the grammar.

The handling of style sheets that do not parse according to the forward-compatible core syntax is not defined by this specification. [Should it be?]

Certain productions within the grammar are error handling points. Every error handling point has a backup production that is to be used if it is not possible to parse the stream of tokens based on the primary production. If the error handling production is represented as prod, then the backup production is represented as FAIL(prod).

[The grammar given in Appendix D of CSS2 still needs to be incorporated into this specification. The editor hopes that it can be done by unifying it with the forward-compatible grammar into a single grammar that describes both the rules for forward-compatible parsing and the syntax of what is currently possible in CSS, but that may not be possible. However, hopefully it will be possible to do this by describing the general grammar in terms of the concepts described in the previous paragraph.]

Excluding the transformation of a production into its backup production, this grammar is LL(1). [We should explain briefly what this means, except that it's probably not true. It's probably just LALR(1).]

The portion of a CSS style sheet that is to be used is the largest initial stream of the tokens resulting from the tokenization process that can be parsed according to the grammar presented in this chapter. (For example, if a brace closing a declaration block [link-ify this] is not present, the declaration block must be ignored since the closing brace is required to satisfy this grammar.) [This might lead to highly unexpected behavior when there's an extra closing brace (etc.). Do we really want this?]

Some of the constraints of CSS are not expressed in the grammar. For example, an @charset rule is not permitted in an embedded style sheet, or a namespace prefix that has not been defined by an @namespace rule is an invalid selector. These constraints should be handled just as a parsing error would be (by ignoring out to the next backup production) unless specified otherwise.

4.3.2. Style sheets

Below is the core syntax for CSS. Lowercase identifiers represent productions in this grammar, uppercase identifiers represent tokens (see above), and characters in single quotes (') represent CHAR tokens (see above). The sections that follow describe how to use it.

[This might need better integration with the selectors module, although maybe it's ok.]

stylesheet  : [ CDO | CDC | S | statement ]*;
statement   : ruleset | at-rule;
at-rule     : ATKEYWORD S* any* [ block | ';' S* ];
block       : '{' S* [ any | block | ATKEYWORD S* | ';' S* ]* '}' S*;
ruleset     : selector? '{' S* declaration? [ ';' S* declaration? ]* '}' S*;
selector    : any+;
declaration : property ':' S* value;
property    : IDENT S*;
value       : [ any | block | ATKEYWORD S* ]+;
any         : [ IDENT | NUMBER | PERCENTAGE | DIMENSION | STRING
              | DELIM | URI | HASH | UNICODE-RANGE | INCLUDES
              | FUNCTION S* any* ')' | DASHMATCH | '(' S* any* ')'
              | '[' S* any* ']' ] S*;
[The definitions of these productions should be spread below into the prose describing what they mean. Furthermore, they should be combined with the Appendix D grammar from CSS2, perhaps using notation like:
ruleset | ::= | ...
FAIL(ruleset) | ::= | ...
]

COMMENT tokens do not occur in the grammar (to keep it readable), but any number of these tokens may appear anywhere between other tokens.

The token S in the grammar above stands for whitespace. Only the characters "space" (Unicode code 32), "tab" (9), "line feed" (10), "carriage return" (13), and "form feed" (12) can occur in whitespace. Other space-like characters, such as "em-space" (8195) and "ideographic space" (12288), are never part of whitespace.

4.4. Keywords

Keywords have the form of identifiers. Keywords must not be placed between quotes ("..." or '...'). Thus,

red

is a keyword, but

"red"

is not. (It is a string.) Other illegal examples:

width: "auto";
border: "none";
background: "red";

4.5. Statements

A CSS style sheet, for any version of CSS, consists of a list of statements (see the grammar above). There are two kinds of statements: at-rules and rule sets. There may be whitespace around the statements.

4.6. At-rules

At-rules start with an at-keyword, an '@' character followed immediately by an identifier (for example, '@import', '@page').

An at-rule consists of everything up to and including the next semicolon (;) or the next block, whichever comes first. A CSS user agent that encounters an unrecognized or misplaced at-rule must ignore the whole of the at-rule and continue parsing after it.

Assume, for example, that a CSS3 parser encounters this style sheet:

@import "subs.css";
h1 { color: blue }
@import "list.css";

The second '@import' is illegal according to CSS3 since '@import' rules must occur before all rules other than '@charset' rules. The CSS3 parser ignores the whole at-rule, effectively reducing the style sheet to:

@import "subs.css";
h1 { color: blue }

In the following example, the second '@import' rule is invalid, since it occurs inside a '@media' block.

@import "subs.css";
@media print {
  @import "print-main.css";
  BODY { font-size: 10pt }
}
h1 {color: blue }

4.7. Blocks

A block starts with a left curly brace ({) and ends with the matching right curly brace (}). In between there may be any characters, except that parentheses (( )), brackets ([ ]) and braces ({ }) must always occur in matching pairs and may be nested. Single (') and double quotes (") must also occur in matching pairs, and characters between them are parsed as a string. See Tokenization above for the definition of a string.

Here is an example of a block. Note that the right brace between the double quotes does not match the opening brace of the block, and that the second single quote is an escaped character, and thus doesn't match the first single quote:

{ causta: "}" + ({7} * '\'') }

Note that the above rule is not valid CSS3, but it is still a block as defined above.

4.8. Rule sets, declaration blocks, and selectors

A rule set (also called "rule") consists of a selector followed by a declaration block.

A declaration-block (also called a {}-block in the following text) starts with a left curly brace ({) and ends with the matching right curly brace (}). In between there must be a list of zero or more semicolon-separated (;) declarations.

The selector (see the Selectors module [SELECT]) consists of everything up to (but not including) the first left curly brace ({). A selector always goes together with a {}-block. When a user agent can't parse the selector (i.e., it is not valid CSS3), it must ignore the {}-block as well.

CSS3 gives a special meaning to the comma (,) in selectors. However, since it is not known if the comma may acquire other meanings in future versions of CSS, the whole statement should be ignored if there is an error anywhere in the selector, even though the rest of the selector may look reasonable in CSS3.

For example, since the "&" is not a valid token in a CSS3 selector, a CSS3 user agent must ignore the whole second line, and not set the color of H3 to red:

h1, h2 {color: green }
h3, h4 & h5 {color: red }
h6 {color: black }

Here is a more complex example. The first two pairs of curly braces are inside a string, and do not mark the end of the selector. This is a valid CSS3 statement.

p[example="public class foo\
{\
    private int x;\
\
    foo(int x) {\
        this.x = x;\
    }\
\
}"] { color: red }

Note. The \ characters in the above example cause the newlines to be ignored. Newlines can be placed in strings only using the correct numeric character escape. See characters and case above.

4.9. Declarations and properties

A declaration is either empty or consists of a property, followed by a colon (:), followed by a value. Around each of these there may be whitespace.

Because of the way selectors work, multiple declarations for the same selector may be organized into semicolon (;) separated groups.

Thus, the following rules:

h1 { font-weight: bold }
h1 { font-size: 2em }
h1 { line-height: 1.2 }
h1 { font-family: Helvetica, Arial, sans-serif }
h1 { font-variant: normal }
h1 { font-style: normal }

are equivalent to:

h1 {
  font-weight: bold;
  font-size: 2em;
  line-height: 1.2;
  font-family: Helvetica, Arial, sans-serif;
  font-variant: normal;
  font-style: normal
}

A property is an identifier. Any character may occur in the value, but parentheses ("( )"), brackets ("[ ]"), braces ("{ }"), single quotes (') and double quotes (") must come in matching pairs, and semicolons not in strings must be escaped. Parentheses, brackets, and braces may be nested. Inside the quotes, characters are parsed as a string.

The syntax of values is specified separately for each property, but in any case, values are built from identifiers, strings, numbers, lengths, percentages, URIs, colors, angles, times, and frequencies.

A user agent must ignore a declaration with an invalid property name or an invalid value. Every CSS3 property has its own syntactic and semantic restrictions on the values it accepts.

For example, assume a CSS3 parser encounters this style sheet:

h1 { color: red; font-style: 12px }  /* Invalid value: 12px */
p { color: blue;  font-vendor: any;  /* Invalid prop.: font-vendor */
    font-variant: small-caps }
em em { font-style: normal }

The second declaration on the first line has an invalid value '12pt'. The second declaration on the second line contains an undefined property 'font-vendor'. The CSS3 parser will ignore these declarations, effectively reducing the style sheet to:

h1 { color: red; }
p { color: blue;  font-variant: small-caps }
em em { font-style: normal }

4.10. Comments

Comments begin with the characters "/*" and end with the characters "*/". They may occur anywhere between tokens, and their contents have no influence on the rendering. Comments may not be nested.

CSS also allows the SGML comment delimiters ("<!--" and "-->") in certain places, but they do not delimit CSS comments. They are permitted so that style rules appearing in an HTML source document (in the STYLE element) may be hidden from pre-HTML 3.2 user agents. See the HTML 4.0 specification ([HTML40]) for more information.

5. Rules for handling parsing errors or unsupported features

[Hopefully (assuming it can be formalized within the rules above) this section will not need so much detail and can be folded into the previous section.]

In some cases, user agents must ignore part of an illegal style sheet. This specification defines ignore to mean that the user agent parses the illegal part according to the grammar above (in order to find its beginning and end), but otherwise acts as if it had not been there.

If a style sheet cannot be parsed according to the grammar above, the user agent must behave the same as it would if the style sheet had the smallest sequence of characters removed from its end that would allow it to be parsed according to the grammar.

To ensure that new properties and new values for existing properties can be added in the future, user agents are required to obey the following rules when they encounter the following scenarios:

  • Unknown properties. User agents must ignore a declaration with an unknown property. For example, if the style sheet is:
    h1 { color: red; rotation: 70minutes }

    the user agent will treat this as if the style sheet had been

    H1 { color: red }
  • Illegal values. User agents must ignore a declaration with an illegal value. For example:
    img { float: left }       /* correct CSS3 */
img { float: left here }  /* "here" is not a value of 'float' */
img { background: "red" } /* keywords cannot be quoted in CSS3 */
img { border-width: 3 }   /* a unit must be specified for length values */
    A CSS3 parser would honor the first rule and ignore the rest, as if the style sheet had been:
    img { float: left }
img { }
img { }
img { }

    A user agent conforming to a future CSS specification may accept one or more of the other rules as well.

    [A general comment on how to handle negative numbers when disallowed might be useful. It should be a parsing error (and thus ignored). We might want to add additional grammar productions for potentially negative numbers.]

  • Malformed declarations. User agents must handle unexpected tokens encountered while parsing a declaration by reading until the end of the declaration, while observing the rules for matching pairs of (), [], {}, "", and '', and correctly handling escapes. For example, a malformed declaration may be missing a property, colon (:) or value. The following are all equivalent:

p { color:green }
p { color:green; color }  /* malformed declaration missing ':', value */
p { color:red;   color; color:green }  /* same with expected recovery */
p { color:green; color: } /* malformed declaration missing value */
p { color:red;   color:; color:green } /* same with expected recovery */
p { color:green; color{;color:maroon} } /* unexpected tokens { } */
p { color:red;   color{;color:maroon}; color:green } /* same with recovery */
  • Invalid at-keywords. User agents must ignore an invalid at-keyword together with everything following it, up to and including the next semicolon (;) or block ({...}), whichever comes first. For example, consider the following:
    @three-dee {
  @background-lighting {
    azimuth: 30deg;
    elevation: 190deg;
  }
  h1 { color: red }
}
h1 { color: blue }

    The '@three-dee' at-rule is not part of CSS3. Therefore, the whole at-rule (up to, and including, the third right curly brace) is ignored. A CSS3 user agent ignores it, effectively reducing the style sheet to:

    h1 { color: blue }

  • Unsupported ValuesIf a UA does not support a particular value, it should ignore that value when parsing stylesheets, as if that value was an illegal value. For example:

      h3 {
    display: inline;
    display: run-in;
  }

    A UA that supports the 'run-in' value for the 'display' property will accept the first display declaration and then "write over" that value with the second display declaration. A UA that does not support the 'run-in' value will process the first display declaration and ignore the second display declaration.

5.1. Partial implementations

CSS3, unlike CSS1 and CSS2, is modular and thus allows for partial implementations. The conformance requirements of some modules may also allow for conformant implementations to implement only part of a module.

Implementations that do not implement a feature of any CSS3 module (whether a property, an at-rule, or a property value) should behave as they would according to the forward-compatible parsing rules had that feature not been part of a known CSS specification.

6. Vendor-specific extensions

Although proprietary extensions should be avoided in general, there are situations (experiments, implementations of W3C drafts that have not yet reached Candidate Recommendation, intra-nets, debugging, etc.) where it is convenient to add some nonstandard, i.e., proprietary identifiers to a CSS style sheet. It is often hard to predict how long these proprietary extensions will be in use and hard to avoid that their names clash with new, standard properties or with other proprietary properties. Therefore the CSS Working Group proposes the following simple naming convention. A proprietary name should have a prefix consisting of:

  1. an underscore ("_") or a dash ("-"),
  2. the (possibly abbreviated) name of the company, organization, etc. that created it,
  3. an underscore or a dash.

Some examples (and the companies/organizations that created them):

  • -moz-box-sizing, -moz-border-radius (The Mozilla Organization)
  • -wap-accesskey (The WAP Forum)
  • _xyz-dwiw (hypothetical)

The advantage of the initial dash is that it is not a valid start character for identifiers in CSS, so it is guaranteed never to be used by any current or future level of CSS. CSS-conforming parsers will skip rules that contain identifiers with such a character. [Should the grammar allow '-' as part of identifiers or should it require that vendors who use '-' to begin identifiers extend the grammar in their tokenizer? Currently it does, but perhaps it shouldn't.]

That is also a possible disadvantage: a conforming parser will skip them, so in order to use them, an extended parser is required.

For that reason, the underscore is also proposed. Although it is a valid start character, the CSS Working Group believes it will never define any identifiers that start with that character.

6.1. Historical notes

This section is informative, not normative.

Microsoft created a number of proprietary properties for use inside their Microsoft Office product, at a time when there was not yet a consensus in the working group about the naming convention. They chose to prefix properties with "mso-" rather than "-mso-".

At the time of writing, the following prefixes are known to exist:

  • mso- (Microsoft Corporation)
  • -moz- (The Mozilla Organization)
  • -opera- (Opera Software)
  • -atsc- (Advanced Television Standards Committee)
  • -wap- (The WAP Forum)

7. Associating style sheets with documents

7.1. Media types

[This section lacks testable statements.]

7.1.1. Introduction to media types

POWERED BY HeroNote

One of the most important features of style sheets is that they specify how a document is to be presented on different media: on the screen, on paper, with a speech synthesizer, with a braille device, etc.

Certain CSS properties are only designed for certain media (e.g., the 'page-break-before' property only applies to paged media). On occasion, however, style sheets for different media types may share a property, but require different values for that property. For example, the 'font-size' property is useful both for screen and print media. The two media types are different enough to require different values for the common property; a document will typically need a larger font on a computer screen than on paper. Therefore, it is necessary to express that a style sheet, or a section of a style sheet, applies to certain media types.

7.1.2. Specifying media-dependent style sheets

There are currently two ways to specify media dependencies for style sheets:

  • Specify the target medium for a set of style rules with the @media at-rule.

    @media print {
  /* style rules for print go here */
}

  • Specify the target media for an entire style sheet at the point where the stylesheet is linked to the document.

    If the style sheet is linked to the document by being imported (with an @import rule) from another style sheet, the target media can be specified as part of the @import at-rule:

    @import url("fancyfonts.css") screen;

    If the style sheet is linked to the document through a linking mechanism within the document, then it may be possible to specify the target medium within the document language. For example, in HTML 4.0 ([HTML40]), the media attribute on the link element specifies the target media of an external style sheet:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
   <head>
      <title>Link to a target medium</title>
      <link rel="stylesheet" type="text/css"
     media="print, handheld" href="foo.css">
   </head>
   <body>
      <p>The body...
   </body>
</html>

7.1.3. The @media rule

An @media rule specifies the target media types (separated by commas) of a set of rules (delimited by curly braces). The @media construct allows style sheet rules for various media in the same style sheet:

  @media print {
    body { font-size: 12pt; }
    h1 { font-size: 24pt; }
  }
  @media screen {
    body { font-size: medium; }
    h1 { font-size: 2em; }
  }
  @media screen, print {
    body { line-height: 1.2; }
  }

7.1.4. Recognized media types

A CSS media type names a set of CSS properties. A user agent that claims to support a media type by name must implement all of the properties that apply to that media type. [This needs to be relaxed to deal with profiles.] (For the 'all' media type, this means that it must support all properties that apply to all media types. [Should all be removed from the list and separated to make this more logical?])

The names chosen for CSS media types reflect target devices for which the relevant properties make sense. The names of media types are normative. In the following list of CSS media types, the parenthetical descriptions are not normative. Likewise, the "Media" field in the description of each property is informative.

all
Suitable for all devices.
braille
Intended for braille tactile feedback devices.
embossed
Intended for paged braille printers.
handheld
Intended for handheld devices (typically small screen, limited bandwidth).
print
Intended for paged material and for documents viewed on screen in print preview mode. Please consult the paged media module [CSS3PAGE] for information about formatting issues that are specific to paged media.
projection
Intended for projected presentations. Please consult the paged media module [CSS3PAGE] for information about formatting issues that are specific to paged media.
screen
Intended primarily for color computer screens.
speech
Intended for speech synthesizers. See the speech module [CSS3SPEECH] for details.
tty
Intended for media using a fixed-pitch character grid (such as teletypes, terminals, or portable devices with limited display capabilities).
tv
Intended for television-type devices (low resolution, color, limited-scrollability screens, sound available).

Media type names are case-insensitive.

Media types are mutually exclusive in the sense that a user agent can only support one media type when rendering a document. However, user agents may have different modes which support different media types.

Note. Future versions of CSS may extend this list. Authors should not rely on media type names that are not yet defined by a CSS specification.

7.1.5. Extensions to media types

The Media Queries Module [MEDIAQ] defines an extended mechanism for media type specification.

7.2. User-agent style sheets

7.3. User style sheets

7.4. Author style sheets

This section is informative, not normative.

[This section should briefly summarize the mechanisms for associating author style sheets with documents provided by [HTML40], [CSSSTYLEATTR] and [XMLSTYLE].]

7.5. Style sheets including other style sheets: the @import rule

[When this section is rewritten to define user agent conformance more clearly, it should state that (1) the media list specified in an @import rule prevents the import from being processed if the medium doesn't match, but it doesn't "associate" the media with the style sheet so that it can't be imported some other way. (2) @import without a medium must ignore any medium specified for the same style sheet in a link from a document.]

[Should the discussion of how imported stylesheets affect the cascade's notion of order be here or in [CSS3CASCADE]? It probably depends on which direction the module dependency goes.]

The '@import' rule allows users to import style rules from other style sheets. Any @import rules must follow all @charset rules and precede all other at-rules and rule sets in a style sheet. The '@import' keyword must be followed by the URI of the style sheet to include. A string is also allowed; it will be interpreted as if it had url(...) around it.

The following lines are equivalent in meaning and illustrate both '@import' syntaxes (one with "url()" and one with a bare string):

@import "mystyle.css";
@import url("mystyle.css");

So that user agents can avoid retrieving resources for unsupported media types, authors may specify media-dependent @import rules. These conditional imports specify comma-separated media types after the URI.

The following rules illustrate how @import rules can be made media-dependent:

@import url("fineprint.css") print;
@import url("bluish.css") projection, tv;

In the absence of any media types, the import is unconditional. Specifying 'all' for the medium has the same effect.

8. Defining namespaces: the @namespace rule

The @namespace rule allows the style sheet author to declare a namespace prefix and associate it to a given namespace URI. The prefix applies only to the style sheet in which it is declared, and not any style sheets imported by that style sheet, style sheets that import that stylesheet, or any other style sheets applying to the document. This namespace prefix can then be used as a namespace prefix as described in other modules, for example the Selectors Module [SELECT] or the Generated Content module [CSS3GENCON]. Any @namespace rules must follow all @import and @charset rules and precede all other at-rules and rule sets in a style sheet. This is to avoid any confusion or issues regarding the scope of the declared namespace.

If the optional namespace prefix is omitted, then the namespace URI is considered to be the default namespace. The default namespace applies only to type selectors that have no explicit namespace prefix declared as described in the Selectors Module [SELECT].

A prefix, once declared, may be used in selectors and property values as described in other modules. Those modules should define the use of a namespace prefix that has not been properly declared as a parsing error that will cause the selector or declaration (etc.) to be considered invalid and ignored.

If a namespace prefix is declared more than once, the last occurrence will be used.

Examples:

@namespace url(http://www.w3.org/1999/xhtml);
@namespace svg url(http://www.w3.org/2000/svg);

The first rule declares a default namespace http://www.w3.org/1999/xhtml to be applied only to type selectors that have no explicit namespace component.

The second rule declares a namespace prefix svg that is used to apply the namespace http://www.w3.org/2000/svg where the svg namespace prefix is used.

9. Conformance

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 (see [RFC2119]). However, for readability, these words do not appear in all uppercase letters in this specification.

At times, this specification recommends good practice for authors and user agents. These recommendations are not normative and conformance with this specification does not depend on their realization. These recommendations contain the expression "We recommend ...", "This specification recommends ...", or some similar wording.

9.1. Definitions

[Some of these need heavy rewriting given modularization. I've avoided substituting CSS3 where it's clearly not going to be appropriate.]

This module and other CSS3 modules rely on the following definitions:

Style sheet
A set of statements that specify presentation of a document.

Style sheets may have three different origins: author, user, and user agent. The interaction of these sources is described in the cascading and inheritance module [CSS3CASCADE].

Valid style sheet
The validity of a style sheet depends on the level of CSS used for the style sheet. All valid CSS1 style sheets are valid CSS 2.1 style sheets, but some changes from CSS1 mean that a few CSS1 style sheets will have slightly different semantics in CSS 2.1. Some features in CSS2 are not part of CSS 2.1, so not all CSS2 style sheets are valid CSS 2.1 style sheets.

A valid CSS 2.1 style sheet must be written according to the grammar of CSS 2.1. Furthermore, it must contain only at-rules, property names, and property values defined in this specification. An illegal (invalid) at-rule, property name, or property value is one that is not valid.

Source document
The document to which one or more style sheets apply. This is encoded in some language that represents the document as a tree of elements. Each element consists of a name that identifies the type of element, optionally a number of attributes, and a (possibly empty) content.
Document language
The encoding language of the source document (e.g., HTML, XHTML or SVG). CSS is used to describe the presentation of document languages and CSS does not change the underlying semantics of the document languages.
Element
(An SGML term, see [ISO8879].) The primary syntactic constructs of the document language. Most CSS style sheet rules use the names of these elements (such as P, TABLE, and OL in HTML) to specify how the elements should be rendered.
Replaced element
An element for which the CSS formatter knows only the intrinsic dimensions. In HTML, IMG and OBJECT elements can be replaced elements. For example, the content of the IMG element is often replaced by the image that the "src" attribute designates.
Intrinsic dimensions
The width and height as defined by the element itself, not imposed by the surroundings. CSS does not define how the intrinsic dimensions are found. In CSS 2.1 it is assumed that all replaced elements, and only replaced elements, come with intrinsic dimensions.
Attribute
A value associated with an element, consisting of a name, and an associated (textual) value.
Content
The content associated with an element in the source document. Some elements have no content, in which case they are called empty. The content of an element may include text, and it may include a number of sub-elements, in which case the element is called the parent of those sub-elements.
Ignore
This term has three slightly different meanings in this specification. First, a CSS parser must follow certain rules when it discovers unknown or illegal syntax in a style sheet. The parser must then ignore certain parts of the style sheets. The exact rules for what parts must be ignored is given in these section: Declarations and properties, Rules for handling parsing errors, Unsupported Values, or may be explained in the text where the term "ignore" appears. Second, a user agent may (and, in some cases must) disregard certain properties or values in the style sheet even if the syntax is legal. For example, table-column-group elements cannot have borders around them, so the border properties must be ignored.
Rendered content
The content of an element after the rendering that applies to it according to the relevant style sheets has been applied. The rendered content of a replaced element comes from outside the source document. Rendered content may also be alternate text for an element (e.g., the value of the XHTML "alt" attribute), and may include items inserted implicitly or explicitly by the style sheet, such as bullets, numbering, etc.
Document tree
The tree of elements encoded in the source document. Each element in this tree has exactly one parent, with the exception of the root element, which has none.
Child
An element A is called the child of element B if and only if B is the parent of A.
Descendant
An element A is called a descendant of an element B, if either (1) A is a child of B, or (2) A is the child of some element C that is a descendant of B.
Ancestor
An element A is called an ancestor of an element B, if and only if B is a descendant of A.
Sibling
An element A is called a sibling of an element B, if and only if B and A share the same parent element. Element A is a preceding sibling if it comes before B in the document tree. Element B is a following sibling if it comes after A in the document tree.
Preceding element
An element A is called a preceding element of an element B, if and only if (1) A is an ancestor of B or (2) A is a preceding sibling of B.
Following element
An element A is called a following element of an element B, if and only if B is a preceding element of A.
Author
An author is a person who writes documents and associated style sheets. An authoring tool generates documents and associated style sheets.
User
A user is a person who interacts with a user agent to view, hear, or otherwise use a document and its associated style sheet. The user may provide a personal style sheet that encodes personal preferences.
User agent (UA)
A user agent is any program that interprets a document written in the document language and applies associated style sheets according to the terms of this specification. A user agent may display a document, read it aloud, cause it to be printed, convert it to another format, etc.
An HTML user agent is one that supports the HTML 2.x, HTML 3.x, or HTML 4.x specifications. A user agent that supports XHTML [XHTML10], but not HTML (as listed in the previous sentence) is not considered an HTML user agent for the purpose of conformance with this specification.

9.2. User agent conformance

[This section should contain rules for user style sheet conformance, author style sheet disabling, handling parsing errors, etc., from the CSS2.1 specification.]

[Below is the text from CSS2.1. Much of it needs rewriting given modularization. I've avoided substituting CSS3 where it's clearly not going to be appropriate.]

This section defines conformance with the CSS 2.1 specification only. There may be other levels of CSS in the future that may require a user agent to implement a different set of features in order to conform.

In general, the following points must be observed by a user agent claiming conformance to this specification:

  1. It must support one or more of the CSS3 media types.
  2. For each source document, it must attempt to retrieve all associated style sheets that are appropriate for the supported media types. If it cannot retrieve all associated style sheets (for instance, because of network errors), it must display the document using those it can retrieve.
  3. It must parse the style sheets according to this specification. In particular, it must recognize all at-rules, blocks, declarations, and selectors (see the grammar of CSS 2.1). If a user agent encounters a property that applies for a supported media type, the user agent must parse the value according to the property definition. This means that the user agent must accept all valid values and must ignore declarations with invalid values. User agents must ignore rules that apply to unsupported media types.
  4. For each element in a document tree, it must assign a value for every applicable property according to the property's definition and the rules of cascading and inheritance.
  5. If the source document comes with alternate style sheet sets (such as with the "alternate" keyword in HTML 4.0 [HTML40]), the UA must allow the user to select which style sheet set the UA should apply.

Not every user agent must observe every point, however:

  • An application that reads style sheets without rendering any content (e.g., a CSS 2.1 validator) must respect points 1-3.
  • An authoring tool is only required to output valid style sheets
  • A user agent that renders a document with associated style sheets must respect points 1-5 and render the document according to the media-specific requirements set forth in this specification. Values may be approximated when required by the user agent.

The inability of a user agent to implement part of this specification due to the limitations of a particular device (e.g., a user agent cannot render colors on a monochrome monitor or page) does not imply non-conformance.

UAs must allow users to specify a file that contains the user style sheet. UAs that run on devices without any means of writing or specifying files are exempted from this requirement. Additionally, UAs may offer other means to specify user preferences, for example through a GUI.

CSS2.1 does not define which properties apply to form controls and frames, or how CSS can be used to style them. User agents may apply CSS properties to these elements. Authors are recommended to treat such support as experimental. A future level of CSS may specify this further.

9.2.1. Error conditions

In general, this document does not specify error handling behavior for user agents (e.g., how they behave when they cannot find a resource designated by a URI).

However, user agents must observe the rules for handling parsing errors.

Since user agents may vary in how they handle error conditions, authors and users must not rely on specific error recovery behavior.

9.3. Style sheet conformance

9.4. Authoring tool conformance

Authoring tools may use a modified form of the rules for handling parsing errors: when those rules require that user agents ignore something, authoring tools are not required to ignore it. However, authoring tools should not present such parts of the style sheet to the user in the same way as valid parts of the style sheet. In so far as authoring tools display the application of a style sheet to a document, they are required to meet the user agent conformance rules.

[informative reference to canonicalization proposal?]

10. Format of property definitions in other modules

Each CSS property definition begins with a summary of key information that resembles the following:

'property-name'
Value: legal values & syntax
Initial: initial value
Applies to: elements this property applies to
Inherited: whether the property is inherited
Computed Value: the computed value of the property
Percentages: how percentage values are interpreted
Media: which media groups the property applies to

10.1. Value

This part specifies the set of valid values for the property. Value types may be designated in several ways:

  1. keyword values (e.g., auto, disc, etc.)
  2. basic data types, which appear between "<" and ">" (e.g., <length>, <percentage>, etc.). In the electronic version of the document, each instance of a basic data type links to its definition.
  3. types that have the same range of values as a property bearing the same name (e.g., <'border-width'> <'background-attachment'>, etc.). In this case, the type name is the property name (complete with quotes) between "<" and ">" (e.g., <'border-width'>). Such a type does not include the value 'inherit'. In the electronic version of the document, each instance of this type of non-terminal links to the corresponding property definition.
  4. non-terminals that do not share the same name as a property. In this case, the non-terminal name appears between "<" and ">", as in <border-width>. Notice the distinction between <border-width> and <'border-width'>; the latter is defined in terms of the former. The definition of a non-terminal is located near its first appearance in the specification. In the electronic version of the document, each instance of this type of value links to the corresponding value definition.

Other words in these definitions are keywords that must appear literally, without quotes (e.g., red). The slash (/) and the comma (,) must also appear literally.

Values may be arranged as follows:

  • Several juxtaposed words mean that all of them must occur, in the given order.
  • A bar (|) separates two or more alternatives: exactly one of them must occur.
  • A double bar (||) separates two or more options: one or more of them must occur, in any order.
  • Brackets ([ ]) are for grouping.

Juxtaposition is stronger than the double bar, and the double bar is stronger than the bar. Thus, the following lines are equivalent:

    a b   |   c || d e
  [ a b ] | [ c || [ d e ]]

Every type, keyword, or bracketed group may be followed by one of the following modifiers:

  • An asterisk (*) indicates that the preceding type, word, or group occurs zero or more times.
  • A plus (+) indicates that the preceding type, word, or group occurs one or more times.
  • A question mark (?) indicates that the preceding type, word, or group is optional.
  • A pair of numbers in curly braces ({A,B}) indicates that the preceding type, word, or group occurs at least A and at most B times.

The following examples illustrate different value types:

Value: N | NW | NE
Value: [ <length> | thick | thin ]{1,4}
Value: [<family-name> , ]* <family-name>
Value: <uri>? <color> [ / <color> ]?
Value: <uri> || <color>

See the values and units [CSS3VAL] module for the formal definitions of the basic values types.

[We need a more formal grammar for parsing of properties. Refer to section on keywords (they can't be quoted).]

10.1.1. initial and inherit values

In addition to the legal values stated, initial and inherit values are also legal for every property. The meaning of these values is described in the Values & Units [CSS3VAL] and Cascading & Inheritance [CSS3CASCADE] modules.

10.2. Initial

This part specifies the property's initial value. If the property is inherited, this is the value that is given to the root element of the document tree. Please consult the the Cascading & Inheritance module [CSS3CASCADE] for information about the interaction between style sheet-specified, inherited, and initial values.

10.3. Applies to

This part lists the elements to which the property applies. All elements are considered to have all properties, but some properties have no rendering effect on some types of elements. For example, 'white-space' only affects block-level elements.

10.4. Inherited

This part indicates whether the value of the property is inherited from an ancestor element by default ("Inherited: yes") or the value of the property is its initial value by default ("Inherited: no"). Please consult the Cascading & Inheritance Module [CSS3CASCADE] for information about the interaction between style sheet-specified, inherited, and initial values.

10.5. Computed value

This part indicates the computed value of the property. The concept of computed value is described in the Cascading & Inheritance Module [CSS3CASCADE]. (It is needed both for inheritance and for the definitions of some DOM properties.)

[What is the computed value for elements to which the property does not apply? Do some existing inherited properties rely on inheritance through elements to which the property doesn't apply?]

10.6. Percentage values

This part indicates how percentages should be interpreted, if they occur in the value of the property. If "N/A" appears here, it means that the property does not accept percentages as values.

10.7. Media groups

[Some of this needs to be relaxed to deal with profiles.]

This section is informative, not normative.

This part indicates the media groups for which the property must be implemented by a conforming user agent. Since properties generally apply to several media, the "Applies to media" section of each property definition lists media groups rather than individual media types. User agents must support the property if they support rendering to the media types included in these media groups. Each property applies to all media types in the media groups listed in its definition.

CSS3 defines the following media groups:

  • continuous or paged.
  • visual, audio, speech, or tactile.
  • grid (for character grid devices), or bitmap.
  • interactive (for devices that allow user interaction), or static (for those that don't).
  • all (includes all media types)

The following table shows the relationships between media groups and media types:

Relationship between media groups and media types
Media Types | Media Groups
 | continuous/paged | visual/audio/speech/tactile | grid/bitmap | interactive/static
braille | continuous | tactile | grid | both
emboss | paged | tactile | grid | static
handheld | both | visual, audio, speech | both | both
print | paged | visual | bitmap | static
projection | paged | visual | bitmap | interactive
screen | continuous | visual, audio | bitmap | both
speech | continuous | speech | N/A | both
tty | continuous | visual | grid | both
tv | both | visual, audio | bitmap | both

10.8. Shorthand properties

Some properties are shorthand properties, meaning they allow authors to specify the values of several properties with a single property.

For instance, the 'font' property is a shorthand property for setting 'font-style', 'font-variant', 'font-weight', 'font-size', 'line-height', and 'font-family' all at once.

The syntax of a shorthand property may allow some of the properties that can be specified by that shorthand to be omitted. When such values are omitted from a shorthand form, each "missing" property is assigned its initial value (see the Cascading & Inheritance module [CSS3CASCADE]). The definition of a shorthand property may further say that it resets the definitions of other properties to their initial value.

The multiple style rules of this example:

h1 {
  font-weight: bold;
  font-size: 2em;
  line-height: 1.2;
  font-family: Helvetica, Arial, sans-serif;
  font-variant: normal;
  font-style: normal;
  font-stretch: normal;
  font-size-adjust: none
}

may be rewritten with a single shorthand property:

h1 { font: bold 2em/1.2 Helvetica, Arial, sans-serif }

In this example, 'font-variant', 'font-stretch', 'font-size-adjust', and 'font-style' take their initial values.

11. Appendix: Second grammar

[This grammar was the Appendix D grammar of CSS2, augmented by the additions from the @namespace draft. It needs to be incorporated into the above normative text in some way.]

The grammar below defines the syntax of CSS2. It is in some sense, however, a superset of CSS2 as this specification imposes additional semantic constraints not expressed in this grammar. A conforming UA must also adhere to the forward-compatible parsing rules, the property and value notation, and the unit notation. In addition, the document language may impose restrictions, e.g. HTML imposes restrictions on the possible values of the "class" attribute.

11.1. Grammar

The grammar below is LL(1) (but note that most UA's should not use it directly, since it doesn't express the forward-compatible parsing conventions, only the CSS3 syntax). The format of the productions is optimized for human consumption and some shorthand notation beyond Yacc (see [YACC]) is used:

[It's probably not LL(1), but rather just LALR(1).]

[This needs a lot more revisions to reflect all the additions in CSS3.]

[This doesn't allow nested at-rules, such as @page inside @media. Do we want to allow this?]

  • *: 0 or more
  • +: 1 or more
  • ?: 0 or 1
  • |: separates alternatives
  • [ ]: grouping

The productions are:

stylesheet
  : [ CHARSET_SYM S* STRING S* ';' ]?
    [S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
    [ namespace [S|CDO|CDC]* ]*
    [ [ ruleset | media | page | font_face ] [S|CDO|CDC]* ]*
  ;
import
  : IMPORT_SYM S*
    [STRING|URI] S* [ medium [ ',' S* medium]* ]? ';' S*
  ;
namespace
  : NAMESPACE_SYM S* [namespace_prefix S*]? [STRING|URI] S* ';' S*
  ;
namespace_prefix
  : IDENT
  ;
media
  : MEDIA_SYM S* medium [ ',' S* medium ]* '{' S* ruleset* '}' S*
  ;
medium
  : IDENT S*
  ;
page
  : PAGE_SYM S* IDENT? pseudo_page? S*
    '{' S* declaration [ ';' S* declaration ]* '}' S*
  ;
pseudo_page
  : ':' IDENT
  ;
font_face
  : FONT_FACE_SYM S*
    '{' S* declaration [ ';' S* declaration ]* '}' S*
  ;
operator
  : '/' S* | ',' S* | /* empty */
  ;
combinator
  : '+' S* | '>' S* | /* empty */
  ;
unary_operator
  : '-' | '+'
  ;
property
  : IDENT S*
  ;
ruleset
  : selector [ ',' S* selector ]*
    '{' S* declaration [ ';' S* declaration ]* '}' S*
  ;
selector
  : simple_selector [ combinator simple_selector ]*
  ;
simple_selector
  : element_name? [ HASH | class | attrib | pseudo ]* S*
  ;
class
  : '.' IDENT
  ;
element_name
  : IDENT | '*'
  ;
attrib
  : '[' S* IDENT S* [ [ '=' | INCLUDES | DASHMATCH ] S*
    [ IDENT | STRING ] S* ]? ']'
  ;
pseudo
  : ':' [ IDENT | FUNCTION S* IDENT S* ')' ]
  ;
declaration
  : property ':' S* expr prio?
  | /* empty */
  ;
prio
  : IMPORTANT_SYM S*
  ;
expr
  : term [ operator term ]*
  ;
term
  : unary_operator?
    [ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* |
      TIME S* | FREQ S* | function ]
  | STRING S* | IDENT S* | URI S* | UNICODERANGE S* | hexcolor
  ;
function
  : FUNCTION S* expr ')' S*
  ;
/*
 * There is a constraint on the color that it must
 * have either 3 or 6 hex-digits (i.e., [0-9a-fA-F])
 * after the "#"; e.g., "#000" is OK, but "#abcd" is not.
 */
hexcolor
  : HASH S*
  ;

11.2. Lexical scanner

The following is the tokenizer, written in Flex (see [FLEX]) notation. The tokenizer is case-insensitive.

The two occurrences of "\377" represent the highest character number that current versions of Flex can deal with (decimal 255). They should be read as "\4177777" (decimal 1114111), which is the highest possible code point in Unicode/ISO-10646, except excluding the characters excluded in the nonascii production above.

%option case-insensitive

h		[0-9a-f]
nonascii	[\200-\377]
unicode		\\{h}{1,6}[ \t\r\n\f]?
escape		{unicode}|\\[ -~\200-\377]
nmstart		[a-z]|{nonascii}|{escape}
nmchar		[a-z0-9-]|{nonascii}|{escape}
string1		\"([\t !#$%&(-~]|\\{nl}|\'|{nonascii}|{escape})*\"
string2		\'([\t !#$%&(-~]|\\{nl}|\"|{nonascii}|{escape})*\'

ident		[-]?{nmstart}{nmchar}*
name		{nmchar}+
num		[0-9]+|[0-9]*"."[0-9]+
string		{string1}|{string2}
url		([!#$%&*-~]|{nonascii}|{escape})*
w		[ \t\r\n\f]*
nl		\n|\r\n|\r|\f
range		\?{1,6}|{h}(\?{0,5}|{h}(\?{0,4}|{h}(\?{0,3}|{h}(\?{0,2}|{h}(\??|{h})))))

%%

[ \t\r\n\f]+		{return S;}

\/\*[^*]*\*+([^/][^*]*\*+)*\/	/* ignore comments */

"<!--"			{return CDO;}
"-->"			{return CDC;}
"~="			{return INCLUDES;}
"|="			{return DASHMATCH;}

{string}		{return STRING;}

{ident}			{return IDENT;}

"#"{name}		{return HASH;}

"@import"		{return IMPORT_SYM;}
"@page"			{return PAGE_SYM;}
"@media"		{return MEDIA_SYM;}
"@font-face"		{return FONT_FACE_SYM;}
"@charset"		{return CHARSET_SYM;}
"@namespace"		{return NAMESPACE_SYM;}

"!{w}important"		{return IMPORTANT_SYM;}

{num}em			{return EMS;}
{num}ex			{return EXS;}
{num}px			{return LENGTH;}
{num}cm			{return LENGTH;}
{num}mm			{return LENGTH;}
{num}in			{return LENGTH;}
{num}pt			{return LENGTH;}
{num}pc			{return LENGTH;}
{num}deg		{return ANGLE;}
{num}rad		{return ANGLE;}
{num}grad		{return ANGLE;}
{num}ms			{return TIME;}
{num}s			{return TIME;}
{num}Hz			{return FREQ;}
{num}kHz		{return FREQ;}
{num}{ident}		{return DIMEN;}
{num}%			{return PERCENTAGE;}
{num}			{return NUMBER;}

"url("{w}{string}{w}")"	{return URI;}
"url("{w}{url}{w}")"	{return URI;}
{ident}"("		{return FUNCTION;}

U\+{range}		{return UNICODERANGE;}
U\+{h}{1,6}-{h}{1,6}	{return UNICODERANGE;}

.			{return *yytext;}

Changes from CSS2

This section is informative.

The parts of CSS2 that have become part of this CSS3 draft are sections 1.3.2 (1.4.2 in CSS 2.1), 1.3.3 (1.4.3 in CSS2.1), 3 (parts), 4.1, 4.2, 4.4, and 6.3, 7, and Appendix D. This draft also contains new material on namespaces and on vendor extensions to CSS that began as separate documents.

  • The text taken from Chapter 1 of CSS2 is now normative rather than informative.
  • added the section on vendor extensions and added the '-' character to the ident productions so that identifiers can begin with it
  • modified the rules for handling parsing errors to allow implementations that support only parts of CSS3
  • described how style sheets that cannot be parsed according to the grammar should be handled (by saying that parsing uses the parseable initial sequence of tokens)
  • [to be done] described handling of unmatched quotation marks (by saying that tokenization uses the tokenizable initial sequence of characters)
  • [to be done] formalized the error handling rules by combining the forward-compatible grammar in chapter 4 with the CSS2 grammar in Appendix D.
  • combined DELIM and other single character tokens into CHAR
  • explicitly stated that the byte order mark should be ignored for purposes of the grammar
  • Changed the acceptable characters to exclude surrogate blocks and #xFFFE, #xFFFF, as in XML.
  • Changed the rules on what to do when a character encoding is not specified.

Acknowledgments

Since most of this draft is taken from CSS2, it would not have been possible to write it so easily without the work of the editors and authors of [CSS1] and [CSS2]. This draft also borrows heavily from earlier drafts on CSS namespace support by Peter Linss [CSS3NAMESPACE] and early (unpublished) drafts on vendor extensions to CSS by Bert Bos. Many current and former members of the working group have contributed to this document. Discussions on www-style@w3.org and in other places have also contributed ideas to this specification. Comments from Glenn Adams, Björn Höhrmann, and Etan Wexler have been particularly helpful.

References

Normative references

[CSS3CASCADE]
Håkon Wium Lie. CSS3 module: Cascading and inheritance. 13 July 2001. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2001/WD-css3-cascade-20010713
[CSS3VAL]
Håkon Wium Lie. CSS3 module: values and units. (forthcoming). W3C working draft. (Work in progress.)
[HTML40]
Raggett, D.; Le Hors, A.; Jacobs, I.. HTML 4.0 Specification (revised). Apr 1998. W3C Recommendation. URL: http://www.w3.org/TR/1998/REC-html40-19980424
[HTTP11]
Fielding, Roy,; et al. Hypertext Transfer Protocol - HTTP/1.1. June 1999. Internet RFC 2616. URL: ftp://ftp.isi.edu/in-notes/rfc2616.txt
[ISO10646]
Information Technology - Universal Multiple- Octet Coded CharacterSet (UCS) - Part 1: Architecture and Basic Multilingual Plane. ISO/IEC10646-1:1993. The current specification also takes into consideration the first five amendments to ISO/IEC 10646-1:1993. Useful <a href="http://www.egt.ie/standards/iso10646/ucs-roadmap.html">roadmaps</a>show which scripts sit at which numeric ranges.
[ISO8879]
Information Processing -- Text and Office Systems -- Standard Generalized Markup Language (SGML). ISO 8879:1986.. URL: http://www.iso.ch/cate/d16387.html
[RFC2045]
N. Freed and N. Borenstein. Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies. November 1996. URL: http://www.ietf.org/rfc/rfc2045.txt
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[RFC2318]
H. Lie, B. Bos, C. Lilley. The text/css Media Type. March 1998.. URL: http://www.ietf.org/rfc/rfc2318.txt
[RFC2978]
N. Freed; J. Postel. IANA Charset Registration Procedures. October 2000. Internet RFC 2978. URL: http://www.ietf.org/rfc/rfc2978.txt
[SELECT]
Daniel Glazman; Tantek Çelik; Ian Hickson; et al. Selectors. 13 Nov 2001. W3C Candidate Recommendation. URL: http://www.w3.org/TR/2001/CR-css3-selectors-20011113
[UNICODE310]
The Unicode Consortium. The Unicode Standard: Version 3.1.0. Addison Wesley Longman. 2000. ISBN 0-201-61633-5. For more information, consult the Unicode Consortium's home page at <a href="http://www.unicode.org/">http://www.unicode.org/</a> URL: http://www.unicode.org/unicode/standard/versions/enumeratedversions.html#Unicode_3_1_0

Other references

[CHARSETS]
Characters sets. These are the official names for character sets that may be used in the Internet and may be referred to in Internet documentation URL: http://www.iana.org/assignments/character-sets
[CSS1]
Håkon Wium Lie; Bert Bos. Cascading Style Sheets, level 1. 1996. W3C Recommendation. Revised 11 Jan 1999. URL: http://www.w3.org/TR/REC-CSS1
[CSS2]
Bert Bos; Håkon Wium Lie; Chris Lilley; Ian Jacobs. Cascading Style Sheets, level 2. 1998. W3C Recommendation. URL: http://www.w3.org/TR/REC-CSS2
[CSS3GENCON]
Håkon Wium Lie; Ian Hickson. CSS3 module: generated text. (forthcoming). W3C working draft. (Work in progress.)
[CSS3NAMESPACE]
Peter Linss. CSS Namespace Enhancements. 25 June 1999. W3C working draft. (Proposal) URL: http://www.w3.org/1999/06/25/WD-css3-namespace-19990625/
[CSS3PAGE]
Robert Stevahn. CSS3 module: paged media. 28 Sep 1999. W3C working draft. (Work in progress) URL: http://www.w3.org/TR/1999/WD-css3-page-19990928
[CSS3SPEECH]
Dave Raggett; Daniel Glazman. CSS3 Speech Module. 14 May 2003. W3C working draft. (Work in progress.) URL: http://www.w3.org/TR/2003/WD-css3-speech-20030514
[CSSSTYLEATTR]
Tantek Çelik; Bert Bos; Marc Attinasi. Syntax of CSS rules in HTML's "style" attribute. 15 May 2002. W3C working draft. (Work in progress.) URL: http://www.w3.org/TR/2002/WD-css-style-attr-20020515
[FLEX]
Flex: The Lexical Scanner Generator. Version 2.3.7, ISBN 1882114213
[MEDIAQ]
Håkon Wium Lie; Tantek Çelik; Daniel Glazman. Media queries. 23 January 2002. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2002/CR-css3-mediaqueries-20020708
[XHTML10]
Steven Pemberton; et al. XHTML 1.0: The Extensible HyperText Markup Language. Jan 2000. W3C Recommendation. URL: http://www.w3.org/TR/2000/REC-xhtml1-20000126
[XML10]
Tim Bray; Jean Paoli; C. M. Sperberg-McQueen; Eve Maler. Extensible Markup Language (XML) 1.0 (Second Edition). Oct 2000. W3C Recommendation. URL: http://www.w3.org/TR/2000/REC-xml-20001006
[XMLSTYLE]
J. Clark. Associating Style Sheets with XML documents. 29 June 1999. W3C Recommendation. URL: http://www.w3.org/TR/xml-stylesheet
[YACC]
S. C. Johnson. YACC - Yet another compiler compiler. Murray Hill. 1975. Technical Report.

Index

  • 'all' media group, #
  • Ancestor, #
  • at-keyword, #
  • At-rules, #, #, #
  • Attribute, #
  • 'audio' media group, #
  • Author, #
  • authoring tool, #
  • backslash escapes, #
  • 'bitmap' media group, #
  • block, #
  • Blocks, #, #
  • byte order mark (BOM), #
  • case sensitivity, #
  • character encoding, #
    • default, #
    • user agent's determination of, #
  • @charset, #, #
  • Child, #
  • color, #
  • COMMENT, #
  • Comments, #, #
  • Comments , #
  • conditional import, #
  • conformance, #
  • Content, #
  • 'continuous' media group, #
  • declaration, #
  • declaration-block, #
  • default
    • character encoding, #
  • Descendant, #
  • Document language, #
  • Document tree, #
  • Element, #
    • following, #
    • preceding, #
  • empty, #
  • error handling points, #
  • following element, #
  • forward-compatible parsing, #
  • 'grid' media group, #
  • identifier, #
  • ignore, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #, #
  • illegal, #
  • '@import', #
  • @import, #, #
  • 'interactive' media group, #
  • Intrinsic dimensions, #
  • ISO-10646, #
  • LL(1), #
  • "MAY", #
  • @media, #, #
  • media-dependent import, #
  • media type, #
  • message entity, #
  • "MUST", #
  • "MUST NOT", #
  • "OPTIONAL", #
  • 'paged' media group, #
  • parent, #
  • preceding element, #
  • property, #
  • 'property-name', #
  • "RECOMMENDED", #
  • Rendered content, #
  • Replaced element, #
  • "REQUIRED", #
  • root, #
  • rule sets, #
  • selector, #, #
  • "SHALL", #
  • "SHALL NOT", #
  • shorthand property, #
  • "SHOULD", #
  • "SHOULD NOT", #
  • Sibling, #
  • Source document, #
  • 'speech' media group, #
  • statements, #
  • 'static' media group, #
  • string, #
  • Style sheet, #
  • 'tactile' media group, #
  • text/css, #, #
  • tokenizer, #
  • UA, #
  • Unicode, #
  • User, #
  • user agent, #
  • User agent (UA), #
  • Valid style sheet, #
  • value, #
  • 'visual' media group, #
  • whitespace, #


CSS3 Multi-column Layout Module

CSS Multi-column Layout Module

W3C Candidate Recommendation 17 December 2009

This version:
http://www.w3.org/TR/2009/CR-css3-multicol-20091217
Latest version:
http://www.w3.org/TR/css3-multicol
Previous version:
http://www.w3.org/TR/2009/WD-css3-multicol-20090630/
Editors:
Håkon Wium Lie, Opera Software, howcome@opera.com

Copyright © 2009 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

This specification describes multi-column layouts in CSS, a style sheet language for the web. Using functionality described in the specification, content can be flowed into multiple columns with a gap and a rule between them.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document was produced by the CSS Working Group as a Candidate Recommendation.

A Candidate Recommendation is a document that has been widely reviewed and ready for implementation. W3C encourages everybody to implement this specification and return comments to the (archived) public mailing list www-style@w3.org (see instructions). When sending e-mail, please put the text “css3-multicol” in the subject, preferably like this: “[css3-multicol] …summary of comment…”

Publication as a Candidate Recommendation does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document has been a Working Draft in the CSS Working Group for several years. Multi-column layouts are traditionally used in print. On screen, multi-column layouts have been considered experimental, and implementation and use experience was deemed necessary in order to proceed. Several implementations have occurred over the past years, and this draft incorporates useful feedback from implementors as well as authors and users.

This document will remain Candidate Recommendation at least until 17 June 2010. See the CR exit criteria.

Table of contents

  • 1. Introduction
  • 2. The multi-column model
  • 3. The number and width of columns
    • 3.1. ‘column-width’
    • 3.2. ‘column-count’
    • 3.3. ‘columns’
    • 3.4. Pseudo-algorithm
    • 3.5. Stacking context
  • 4. Column gaps and rules
    • 4.1. ‘column-gap’
    • 4.2. ‘column-rule-color’
    • 4.3. ‘column-rule-style’
    • 4.4. ‘column-rule-width’
    • 4.5. ‘column-rule’
  • 5. Column breaks
  • 6. Spanning columns
    • 6.1. ‘column-span’
  • 7. Filling columns
  • 8. Overflow and multicol elements
    • 8.1. Overflow inside multicol elements
    • 8.2. Overflow outside multicol elements
  • 9. Conformance
    • 9.1. CR exit criteria
  • Acknowledgments
  • References
    • Normative references
    • Other references
  • Index
  • Property index

1. Introduction

(This section is not normative.)

This module describes multi-column layout in CSS. By using functionality described in this document, style sheets can declare that the content of an element is to be laid out in multiple columns.

On the Web, tables have also been used to describe multi-column layouts. The main benefit of using CSS-based columns is flexibility; content can flow from one column to another, and the number of columns can vary depending on the size of the viewport. Removing presentation table markup from documents allows them to more easily be presented on various output devices including speech synthesizers and small mobile devices.

Multi-column layouts are easy to describe in CSS. Here is a simple example:

body { column-width: 12em }

In this example, the body element is set to have columns at least ‘12em’ wide. The exact number of columns will depend on the available space.

The number of columns can also be set explicitly in the style sheet:

body { column-count: 2 }

In this case, the number of columns is fixed and the column widths will vary depending on the available width.

The shorthand ‘columns’ property can be used to set either, or both, properties in one declaration.

In this example, but the number and widths of columns is set:

body { columns: 2 }
body { columns: 12em }
body { columns: 2 12em }

Setting both properties rarely makes sense, as described below.

Another group of properties introduced in this module describe gaps and rules between columns.

body {
  column-gap: 1em;
  column-rule: thin solid black;
}

The first declaration in the example above sets the gap between two adjacent columns to be 1em. Column gaps are similar to padding areas. In the middle of the gap there will be a rule which is described by the ‘column-rule’ property.

The values of the ‘column-rule’ property are similar to those of the CSS border properties. Like ‘border’, ‘column-rule’ is a shorthand property.

In this example, the shorthand ‘column-rule’ declaration from the above example has been expanded:

body {
  column-gap: 1em;
  column-rule-width: thin;
  column-rule-style: solid;
  column-rule-color: black;
}

The ‘column-fill’ and ‘column-span’ properties give style sheets a wider range of visual expressions in multi-column layouts.

In this example, columns are set to be balanced, i.e., to have approximately the same length. Also, h2 elements are set to span across all columns.

div { column-fill: balance }
h2 { column-span: all }

This specification introduces ten new properties, all of which are used in the examples above.

To indicate where column breaks should (or should not) appear, new keyword values are introduced.

In this example, h1 elements will always have a column break before them, but the formatter will try to avoid column breaks inside and after the element.

h1 {
  break-before: column;
  break-inside: avoid-column;
  break-after: avoid-column;
}

If all column properties have their initial value, the layout of an element will be identical to a multi-column layout with only one column.

2. The multi-column model

A multi-column element (or multicol element for short) is an element whose ‘column-width’ or ‘column-count’ property is not ‘auto’ and therefore acts as a container for multi-column layout.

In the traditional CSS box model, the content of an element is flowed into the content box of the corresponding element. Multi-column layout introduces a new type of container between the content box and the content, namely the column box (or column for short). The content of a multicol element is flowed into its column boxes.

Column boxes in a multi-column element are arranged into rows. Like table cells, the column boxes in a row are ordered in the inline direction of the multicol element. The column width is the length of the column box in the inline direction. The column height is the length of the column box in the block direction. All column boxes in a multi-column element have the same column width, and all column boxes in a row have the same column height. Within each row in the multi-column element, adjacent column boxes are separated by a column gap, which may contain a column rule. All column gaps in the same row are equal. All column rules in the same row are also equal, if the appear; column rows only appear between columns that both have content.

In the simplest case a multicol element will contain only one row of columns, and the height of each column will be equivalent to the used height of the multi-column element's content box. If the multi-column element is paginated, then the height of each row is constrained by the page, and the content continues in a new row of column boxes on the next page; a column box never splits across pages. The same effect occurs when a spanning element divides the multi-column element: the columns before the spanning element are balanced and shortened to fit their content. Content after the spanning element then flows into a new row of column boxes.

It is not possible to set properties/values on column boxes. For example, the background of a certain column box cannot be set and a column box has no concept of padding, margin or borders.

Future specifications may add additional functionality. For example, columns of different widths and different backgrounds may be supported.

Column gaps (yellow) and column rules (green) are shown in this sample rendition of a multi-column element with padding (blue). The blue and yellow is present for illustrational purposes only. In actual implementations these ares will be determined by the background.

Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.
M nop qrst uv wx yz.
Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs

tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.
M nop qrst uv wx yz.
Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.

M nop qrst uv wx yz.
Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.
M nop qrst uv wx yz.
Ab cde fgh i jkl. Mno
Pqr stu vw xyz.

To illustrate the effects of the various properties described in this specification, variations on a sample document will be used. Here is the source code of the sample document:

<html>
<style type="text/css">
div {
  column-width: 15em;
  column-gap: 2em;   /* shown in yellow */
  column-rule: 4px solid green;
  padding: 5px;      /* shown in blue */
}
p { margin: 0; padding: 0 }
img { display: none }
</style>
<body>
<div>
<p>Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
<img src=...>
def g hij
...
</div>
</body>
</html>

The nonsensical text in the example is the English alphabet which shows how text flows from one column to another. To simplify the visualization, the textual content of the different examples vary slightly.

Column boxes act as the containing block for their content. That is, column boxes behave like block-level, table cell, and inline-block boxes as per CSS 2.1, section 10.1, item 2 [CSS21]. However, column boxes do not establish containing blocks for elements with ‘position: fixed’ or ‘position: absolute’.

In this example, the width of the image is set with these rules:

img { display: block; width: 100% }

Given that the width is calculated relative to the column box, the image will be as wide as the column box:

Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc

def g hij klm nopqrs
tuv wxy z. Abc de fg

hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.
M nop qrst uv wx yz.
Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.
M nop qrst uv wx yz.

Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.
M nop qrst uv wx yz.
Ab cde fgh i jkl. Mno
pqr stu vw xyz.

Floats that appear inside multi-column layouts are positioned with regard to the column box where the float appears.

In this example, this CSS fragment describes the presentation of the image:

img { display: block; float: right }

Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g
hij klm
nopq
rs tuv
wxy x
yz. Ab
cde fgh i jkl. Mno
pqr stu vw xyz. A bc

def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.
M nop qrst uv wx yz.
Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw

x yz. Abc def ghi jkl.
M nop qrst uv wx yz.
Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.
M nop qrst uv wx yz.

The black box represents the image.

A multi-column element establishes a new block formatting context, as per CSS 2.1 section 9.4.1.

A top margin set on the first child element of a multicol element will not collapse with the margins of the multicol element.

Nested multi-column elements are allowed, but there may be implementation-specific limits.

3. The number and width of columns

Finding the number and width of columns is fundamental when laying out multi-column content. When the block direction is unconstrained and no column breaks are added through style sheets, these two properties determine the outcome:

  • ‘column-count’
  • ‘column-width’

A third property, ‘columns’, is a shorthand property which sets both ‘column-width’ and ‘column-count’.

3.1. ‘column-width’

Name: | column-width
Value: | <length> | auto
Initial: | auto
Applies to: | non-replaced block-level elements (except table elements), table cells, and inline-block elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | the absolute length

This property describes the width of columns in multicol elements.

auto
means that the column width will be determined by other properties (e.g., ‘column-count’, if it has a non-auto value).
<length>
describes the optimal column width. The actual column width may be wider (to fill the available space), or narrower (only if the available space is smaller than the specified column width). Values must be greater than 0.

For example, consider this style sheet:

div {
  width: 100px;
  column-width: 45px;
  column-gap: 0;
  column-rule: none;
}

There is room for two 45px wide columns inside the 100px wide element. In order to fill the available space the actual column width will be increased to 50px.

Also, consider this style sheet:

div {
  width: 40px;
  column-width: 45px;
  column-gap: 0;
  column-rule: none;
}

The available space is smaller than the specified column width and the actual column width will therefore be decreased.

To ensure that ‘column-width’ can be used with vertical text, column width means the length of the line boxes inside the columns.

The reason for making ‘column-width’ somewhat flexible is to achieve scalable designs that can fit many screen sizes. To set an exact column width, all length values (in horizontal text these are: ‘width’, ‘column-width’, ‘column-gap’, and ‘column-rule-width’) must be specified.

3.2. ‘column-count’

Name: | column-count
Value: | <integer> | auto
Initial: | auto
Applies to: | non-replaced block-level elements (except table elements), table cells, and inline-block elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified value

This property describes the number of columns of a multicol element.

auto
means that the number of columns will be determined by other properties (e.g., ‘column-width’, if it has a non-auto value).
<integer>
describes the optimal number of columns into which the content of the element will be flowed. Values must be greater than 0. If both ‘column-width’ and ‘column-count’ have non-auto values, the integer value describes the maximum number of columns.

Example:

body { column-count: 3 }

3.3. ‘columns’

Name: | columns
Value: | <‘column-width’> || <‘column-count’>
Initial: | see individual properties
Applies to: | non-replaced block-level elements (except table elements), table cells, and inline-block elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | see individual properties

This is a shorthand property for setting ‘column-width’ and ‘column-count’. Omitted values are set to their initial values.

Here are some valid declarations using the ‘columns’ property:

columns: 12em;      /* column-width: 12em; column-count: auto */
columns: auto 12em; /* column-width: 12em; column-count: auto */
columns: 2;         /* column-width: auto; column-count: 2 */
columns: 2 auto;    /* column-width: auto; column-count: 2 */
columns: auto;      /* column-width: auto; column-count: auto */
columns: auto auto; /* column-width: auto; column-count: auto */

3.4. Pseudo-algorithm

The pseudo-algorithm below determines the used values for ‘column-count’ (N) and ‘column-width’ (W). There are two other variables in the pseudo-algorithm:

  • available-width: if the used width of the multi-column element has not been determined when the ‘column-count’ and ‘column-width’ must be determined (e.g., if it is floating with a ‘width’ of ‘auto’ as per CSS 2.1 section 10.3.5) this variable is unknown, otherwise it is the same as the used width of the multi-column element. In vertical text, the used height replaces used width in this calculation.
  • shrink-to-fit: this variable represents the result of a shrink-to-fit computation. CSS does not define the exact algorithm.

Two assumptions are being made by the pseudo-algorithm:

  • that the block direction is unconstrained
  • that no column breaks are added through style sheets

The floor() function rounds a number to the next smaller integer.

(01)  if ((column-width = auto) and (column-count = auto)) or
(02)     ((available-width = unknown) and (column-count = auto)) then
(03)    exit; /* no columns */
(04)  fi
(05)
(06)  if (available-width = unknown) and (column-count != auto) and (column-width != auto) then
(07)    N := column-count;
(08)    W := column-width;
(09)    exit;
(10)  fi
(11)
(12)  if (available-width = unknown) then
(13)    available-width := shrink-to-fit;
(14)  fi
(15)
(16)  if (column-width = auto) then
(17)    if ((column-count - 1) * column-gap < available-width) then
(18)      N := column-count;
(19)      W := (available-width - ((N - 1) * column-gap))/N;
(20)    elsif (column-gap >= available-width) then
(21)      N := 1;
(22)      W := available-width;
(23)    else
(24)      N := floor(available-width/column-gap);
(25)      W := (available-width - ((N - 1) * column-gap))/N;
(26)    fi
(27)  elsif (column-count = auto) then
(28)    if (column-width >= available-width) then
(29)      N := 1
(30)      W := available-width;
(31)    else
(32)      N := floor((available-width + column-gap) / (column-width + column-gap));
(33)      W := ((available-width + column-gap) / N) - column-gap;
(34)    fi
(35)  elsif (column-width >= available-width) then
(36)    N := 1
(37)    W := available-width;
(38)  else
(39)    N := floor((available-width + column-gap) / (column-width + column-gap));
(40)    W := ((available-width + column-gap) / N) - column-gap;
(41)  fi

In paged media, user agents may perform this calculation on a per-page basis.

Note that, in most cases, only one of ‘column-width’ and ‘column-count’ affect the layout. If ‘column-width’ has a value other than ‘auto’, ‘column-count’ will be ignored. The only case when both ‘column-width’ and ‘column-count’ can affect the layout is for element where the width of the element has not been determined. This can, e.g., be the case for table cells and floats.

3.5. Stacking context

All column boxes in a multi-column element are in the same stacking context and the drawing order of their contents is as specified in CSS 2.1.

4. Column gaps and rules

Column gaps and rules are placed between columns in the same multicol element. The length of the column gaps and column rules is equal to the length of the columns. Column gaps take up space. That is, column gaps will push apart content in adjacent columns (within the same multicol element).

A column rule is drawn in the middle of the column gap with the endpoints at opposing content edges of the multicol element. Column rules do not take up space. That is, the presence or thickness of a column rule will not alter the placement of anything else. If a column rule is wider than its gap, the column rule will overlap adjacent column boxes. Column rules are painted just above the background of the multicol element. This allows child elements with ‘z-index’ values to be on top of column rules. Column rules are only drawn between two columns that both have content.

4.1. ‘column-gap’

POWERED BY HeroNote
Name: | column-gap
Value: | <length> | normal
Initial: | normal
Applies to: | multicol elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | absolute length or ‘normal’

The ‘column-gap’ property sets the gap between columns. If there is a column rule between columns, it will appear in the middle of the gap.

The ‘normal’ value is UA-specific. A value of ‘1em’ is suggested.

Column gaps cannot be negative.

4.2. ‘column-rule-color’

Name: | column-rule-color
Value: | <color>
Initial: | same as for ‘color’ property [CSS21]
Applies to: | multicol elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | the same as the computed value for the ‘color’ property [CSS21]

This property sets the color of the column rule. The <color> values are defined in [CSS21].

4.3. ‘column-rule-style’

Name: | column-rule-style
Value: | <‘border-style’>
Initial: | none
Applies to: | multicol elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified value

The ‘column-rule-style’ property sets the style of the rule between columns of an element. The <border-style> values are defined in [CSS21].

The ‘inset’ keyword value is shown like the ‘ridge’ value. The ‘outset’ value is shown like ‘groove’.

The ‘none’ value forces the computed value of ‘column-rule-width’ to be ‘0’.

4.4. ‘column-rule-width’

Name: | column-rule-width
Value: | <‘border-width’>
Initial: | medium
Applies to: | multicol elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | absolute length; ‘0’ if the column rule style is ‘none’ or ‘hidden’

This property sets the width of the rule between columns. Negative values are not allowed.

4.5. ‘column-rule’

Name: | column-rule
Value: | <column-rule-width> || <border-style> || [ <color> | transparent ]
Initial: | see individual properties
Applies to: | multicol elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | see individual properties

This property is a shorthand for setting ‘column-rule-width’, ‘column-rule-style’, and ‘column-rule-color’ at the same place in the style sheet. Omitted values are set to their initial values.

In this example, the column rule and the column gap have the same width. Therefore, they will occupy exactly the same space.

body {
  column-gap: 1em;
  column-rule-width: 1em;
  column-rule-style: solid;
  column-rule-color: black;
}

If a tall image is moved to a column on the next page to find room for it, its natural column may be left empty. If so, the column is is still considered to have content for the purpose of deciding if the column rule should be drawn.

5. Column breaks

When content is laid out in multiple columns, the user agent must determine where column breaks are placed. The problem of breaking content into columns is similar to breaking content into pages.

Three new properties are introduced to allow column breaks to be described in the same properties as page breaks: ‘break-before’, ‘break-after’, and ‘break-inside’. These properties take the same values as ‘page-break-before’, ‘page-break-after’, and ‘page-break-inside’ [CSS21]. In addition, some new keyword values are added.

Name: | break-before
Value: | auto | always | avoid | left | right | page | column | avoid-page | avoid-column
Initial: | auto
Applies to: | block-level elements
Inherited: | no
Percentages: | N/A
Media: | paged
Computed value: | specified value
Name: | break-after
Value: | auto | always | avoid | left | right | page | column | avoid-page | avoid-column
Initial: | auto
Applies to: | block-level elements
Inherited: | no
Percentages: | N/A
Media: | paged
Computed value: | specified value
Name: | break-inside
Value: | auto | avoid | avoid-page | avoid-column
Initial: | auto
Applies to: | block-level elements
Inherited: | no
Percentages: | N/A
Media: | paged
Computed value: | specified value

These properties describe page/column break behavior before/after/inside the generated box. These are normatively defined in [CSS21]:

auto
Neither force nor forbid a page/column break before (after, inside) the generated box.
always
Always force a page break before (after) the generated box.
avoid
Avoid a page/column break before (after, inside) the generated box.
left
Force one or two page breaks before (after) the generated box so that the next page is formatted as a left page.
right
Force one or two page breaks before (after) the generated box so that the next page is formatted as a right page.

This specification adds the following new values:

page
Always force a page break before (after) the generated box.
column
Always force a column break before (after) the generated box.
avoid-page
Avoid a page break before (after, inside) the generated box.
avoid-column
Avoid a column break before (after, inside) the generated box.

When a page or column break splits a box, the box's margins, borders, and padding have no visual effect where the split occurs. However, the margin immediately after a forced page/column break will be preserved. A forced page/column break is a break that does not occur naturally.

In the future, new properties may describe alternate ways to handle margins, borders and padding around page/column breaks.

In this example, forced column breaks appear before h2 elements and after img elements:

.multicol { column-width: 8em }
.multicol h2 { break-before: column; margin-top: 2em }
.multicol img { break-after: column }

The top margin of h2 elements will be preserved since the column break is forced.

In this example, the formatter will try avoid column breaks inside p elements:

p { break-inside: avoid-column }

6. Spanning columns

The ‘column-span’ property makes it possible for an element to span across several columns.

6.1. ‘column-span’

Name: | column-span
Value: | 1 | all
Initial: | 1
Applies to: | static, non-floating elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | as specified

This property describes how many columns an element spans across. Values are:

1
The element does not span multiple columns.
all
The element spans across all columns. Content in the normal flow that appears before the element is automatically balanced across all columns before the element appears.

An element that spans more than one column is called a spanning element.

In this example, an h2 element has been added to the sample document after the first sentence in the fourth alphabet (i.e., after the word "jkl."). This styling applies:

h2 { column-span: all; background: silver }
img { display: none }

By setting ‘column-span’ to ‘all’, all content that appear before the h2 element is shown before the h2 element.

Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc

M nop qrst uv wx yz.
Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw

def g hij klm nopqrs
tuv wxy z. Abc de fg

x yz. Abc def ghi jkl.
M nop qrst uv wx yz.
Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg

hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.

hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.
M nop qrst uv wx yz.
Ab cde fgh i jkl. Mno
pqr stu vw xyz.

An H2 element

7. Filling columns

There are two strategies for filling columns: columns can either be balanced, or not. If columns are balanced, UAs should minimize the variation in column length. Otherwise, columns are filled sequentially and will therefore end up having different lengths. In any case, the user agent should try to honor the ‘widows’ and ‘orphans’ properties.

Name: | column-fill
Value: | auto | balance
Initial: | balance
Applies to: | multi-column elements
Inherited: | no
Percentages: | N/A
Media: | see below
Computed value: | as specified

The values are:

balance
Balance content equally between columns, if possible.
auto
Fills columns sequentially.

In continuous media, this property will only be consulted if the length of columns has been constrained. Otherwise, columns will automatically be balanced.

8. Overflow and multicol elements

8.1. Overflow inside multicol elements

Content in the normal flow that extends into column gaps (e.g., long words or images) is clipped in the middle of the column gap.

In this example, the black image is wider than the column, and is therefore clipped.

Lorem ipsum dolor
sit amet. Nam at jus.

Sed imp er di et ris.
Cur abi tur et sapen.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

Lorem ipsum dolor
sit amet. Nam at jus.
Sed imp er di et ris.
Cur abi tur et sapen.
Vivamus a metus.
Aenean at risus
pharetra ante luctu
feugiat quis enim.
Cum sociis natoque
penatibus et magni.

8.2. Overflow outside multicol elements

Content that extend outside column boxes at the edges of the multi-column element is clipped according to the ‘overflow’ property.

A multicol element can have more columns than it has room for due to:

  • Constrained column height. A declaration that constrains the column height (e.g., using ‘height’) must be honored, if possible. In paged media, the column height is constrained by the size of the page.
  • Explicit column breaks. Explicit column breaks may create more columns than there is room for inside the multicol element.

In continuous media, columns that do not fit within the multicol element are added in the inline direction.

In this example, the height of the multi-column element has been constrained to a maximum height. Also, the style sheet specifies that overflowing content should be visible:

div {
  max-height: 5em;
  overflow: visible;
}

As a result, the number of columns is increased.

Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw

x yz. Abc def ghi jkl.
M nop qrst uv wx yz.
Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs

tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.
M nop qrst uv wx yz.
Ab cde fgh i jkl. Mno

pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno. Pqrstu vw
x yz. Abc def ghi jkl.

In this example, explicit column breaks are generated after paragraphs:

p {
  break-after: column;
}

As a result, the number of columns is increased:

Ab cde fgh i jkl. Mno
pqr stu vw xyz.

Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z.

Ab cde fgh i jkl mno.

Pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno pqr stu v
wx yz.

In paged media, columns that do not fit within the page are moved to the next page.

In this example, explicit column breaks are generated after paragraphs:

p {
  break-after: column;
}

As a result, the number of columns is increased and placed on the next page. This would appear on the first page:

Ab cde fgh i jkl. Mno
pqr stu vw xyz.

Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z.

Ab cde fgh i jkl.

This would appear on the second page:

Ab cde fgh i jkl. Mno
pqr stu vw xyz. A bc
def g hij klm nopqrs
tuv wxy z. Abc de fg
hi jklmno.

9. Conformance

Conforming UAs must flow the content of an element into several columns according to this specification.

The conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification. All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

9.1. CR exit criteria

As described in the W3C process document, a Candidate Recommendation (CR) is a specification that W3C recommends for use on the Web. The next stage is Recommendation, when the specification is sufficiently implemented.

For this specification to be proposed as a W3C Recommendation, the following conditions shall be met. There must be at least two independent, interoperable implementations of each feature. Each feature may be implemented by a different set of products, there is no requirement that all features be implemented by a single product. For the purposes of this criterion, we define the following terms:

independent
each implementation must be developed by a different party and cannot share, reuse, or derive from code used by another qualifying implementation. Sections of code that have no bearing on the implementation of this specification are exempt from this requirement.
interoperable
passing the respective test case(s) in the official CSS test suite, or, if the implementation is not a Web browser, an equivalent test. Every relevant test in the test suite should have an equivalent test created if such a user agent (UA) is to be used to claim interoperability. In addition if such a UA is to be used to claim interoperability, then there must one or more additional UAs which can also pass those equivalent tests in the same way for the purpose of interoperability. The equivalent tests must be made publicly available for the purposes of peer review.
implementation
a user agent which:
  1. implements the specification.
  2. is available to the general public. The implementation may be a shipping product or other publicly available version (i.e., beta version, preview release, or nightly build). Non-shipping product releases must have implemented the feature(s) for a period of at least one month in order to demonstrate stability.
  3. is not experimental (i.e., a version specifically designed to pass the test suite and is not intended for normal usage going forward).

A minimum of sixth months of the CR period must have elapsed. This is to ensure that enough time is given for any remaining major errors to be caught.

Features will be dropped if two or more interoperable implementations are not found by the end of the CR period.

Features may/will also be dropped if adequate/sufficient (by judgment of CSS WG) tests have not been produced for those feature(s) by the end of the CR period.

Acknowledgments

This document is based on several older proposals and comments on older proposals. Contributors include Sylvain Galineau, Giovanni Campagna, David Hyatt, David Singer, David Woolley, Elika Etemad, Björn Höhrmann, Joost de Valk, Peter-Paul Koch, Till Halbach, Cédric Savarese, Andy Clarke, Robert O'Callahan, Markus Mielke, Alex Mogilevsky, Sergey Genkin, Michael Day, Melinda Grant, Kevin Lawver, David Baron, Bert Bos, Dave Raggett, Chris Wilson, Robert Stevahn, Peter Linss, Chris Lilley, Steve Zilles, Tantek Çelik, Daniel Glazman and Ian Hickson.

References

Normative references

[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 8 September 2009. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2009/CR-CSS2-20090908
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt

Other references

Index

  • break-after, 5.
  • break-before, 5.
  • break-inside, 5.
  • column box, 2.
  • column-count, 3.2.
  • column-fill, 7.
  • column-gap, 4.1.
  • column-rule, 4.5.
  • column-rule-color, 4.2.
  • column-rule-style, 4.3.
  • column-rule-width, 4.4.
  • columns, 3.3.
  • column-span, 6.1.
  • column-width, 3.1.
  • multi-column element, 2.
  • spanning element, 6.1.

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
break-after | auto | always | avoid | left | right | page | column | avoid-page | avoid-column | auto | block-level elements | no | N/A | paged
break-before | auto | always | avoid | left | right | page | column | avoid-page | avoid-column | auto | block-level elements | no | N/A | paged
break-inside | auto | avoid | avoid-page | avoid-column | auto | block-level elements | no | N/A | paged
column-count | <integer> | auto | auto | non-replaced block-level elements (except table elements), table cells, and inline-block elements | no | N/A | visual
column-fill | auto | balance | balance | multi-column elements | no | N/A | see below
column-gap | <length> | normal | normal | multicol elements | no | N/A | visual
column-rule | <column-rule-width> || <border-style> || [ <color> | transparent ] | see individual properties | multicol elements | no | N/A | visual
column-rule-color | <color> | same as for ‘color’ property [CSS21] | multicol elements | no | N/A | visual
column-rule-style | <‘border-style’> | none | multicol elements | no | N/A | visual
column-rule-width | <‘border-width’> | medium | multicol elements | no | N/A | visual
columns | <‘column-width’> || <‘column-count’> | see individual properties | non-replaced block-level elements (except table elements), table cells, and inline-block elements | no | N/A | visual
column-span | 1 | all | 1 | static, non-floating elements | no | N/A | visual
column-width | <length> | auto | auto | non-replaced block-level elements (except table elements), table cells, and inline-block elements | no | N/A | visual


CSS3 Namespaces Module

CSS Namespaces Module

W3C Candidate Recommendation 23 May 2008

This version:
http://www.w3.org/TR/2008/CR-css3-namespace-20080523/
Latest version:
http://www.w3.org/TR/css3-namespace/
Previous version:
http://www.w3.org/TR/2008/WD-css3-namespace-20080215/
Editors:
Elika J. Etemad
Anne van Kesteren
Previous Editors:
Peter Linss, Netscape Communications
Chris Lilley, W3C

Copyright © 2008 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

This CSS Namespaces module defines the syntax for using namespaces in CSS. It defines the @namespace rule for declaring the default namespace and binding namespaces to namespace prefixes, and it also defines a syntax that other specifications can adopt for using those prefixes in namespace-qualified names.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document was produced by the CSS Working Group as a Candidate Recommendation.

A Candidate Recommendation is a document that has been widely reviewed and ready for implementation. W3C encourages everybody to implement this specification and return comments to the (archived) public mailing list www-style@w3.org (see instructions). When sending e-mail, please put the text “css3-namespace” in the subject, preferably like this: “[css3-namespace] …summary of comment…”

Publication as a Candidate Recommendation does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

For this specification to exit the CR stage, the following conditions shall be met:

  1. There must be at least two interoperable implementations. For the purposes of this criterion, we define the following terms:

    interoperable

    passing the respective test case(s) in the CSS test suite, or, if the implementation is not a Web browser, an equivalent test. Every relevant test in the test suite should have an equivalent test created if such a user agent (UA) is to be used to claim interoperability. In addition if such a UA is to be used to claim interoperability, then there must one or more additional UAs which can also pass those equivalent tests in the same way for the purpose of interoperability. The equivalent tests must be made publicly available for the purposes of peer review.

    implementation

    a user agent which:

    1. implements the specification.
    2. is available (i.e. publicly downloadable or available through some other public point of sale mechanism). This is the "show me" requirement.
    3. is shipped, or is a "nightly build" (i.e., a development version for the next release), but is not experimental (i.e., a version specifically designed to pass the test suite and not intended for daily usage going forward).

  2. A minimum of another three months of the CR period must elapse. That is, this specification will not exit CR before 23 August 2008. When the specification exits CR, an implementation report will be published. At this point, no such report exists.

  3. The specified technology must not be harmful for accessibility.

A CSS Namespace Test Suite will be developed during the Candidate Recommendation phase of this CSS Namespaces specification.

Comments on and subsequent changes since the last Working Draft are listed in the separate Disposition of Comments.

Table of contents

  • 1. Introduction
  • 2. Conformance
    • 2.1 Terminology
  • 3. Declaring namespaces: the @namespace rule
    • 3.1 Syntax
    • 3.2 Scope
    • 3.3 Declaring Prefixes
  • 4. CSS Qualified Names
  • Acknowledgments
  • References
    • Normative references
    • Informative references
POWERED BY HeroNote

1. Introduction

This section is non-normative.

This CSS Namespaces module defines syntax for using namespaces in CSS. It defines the @namespace rule for declaring a default namespace and for binding namespaces to namespace prefixes. It also defines a syntax for using those prefixes to represent namespace-qualified names. It does not define where such names are valid or what they mean: that depends on their context and is defined by a host language, such as Selectors ([SELECT]), that references the syntax defined in the CSS Namespaces module.

Note that a CSS client that does not support this module will (if it properly conforms to CSS's forward-compatible parsing rules) ignore all @namespace rules, as well as all style rules that make use of namespace qualified names. The syntax of delimiting namespace prefixes in CSS was deliberately chosen so that these CSS clients would ignore the style rules rather than possibly match them incorrectly.

2. Conformance

A document or implementation cannot conform to CSS Namespaces alone, but can claim conformance to CSS Namespaces if it satisfies the conformance requirements in this specification when implementing CSS or another host language that normatively references this specification.

Conformance to CSS Namespaces is defined for two classes:

style sheet
A CSS style sheet (or a complete unit of another host language that normatively references CSS Namespaces).
interpreter
Someone or something that interprets the semantics of a style sheet. (CSS user agents fall under this category.)

The conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification. All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words "for example" or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word "Note" and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

2.1 Terminology

Besides terms introduced by this specification, CSS Namespaces uses the terminology defined in Namespaces in XML 1.0. [XML-NAMES] However, the syntax defined here is not restricted to representing XML element and attribute names and may represent other kinds of namespaces as defined by the host language.

In CSS Namespaces a namespace name consisting of the empty string is taken to represent the null namespace or lack of a namespace.

For example, given the namespace declarations:

@namespace empty "";
@namespace "";

The type selectors elem, |elem, and empty|elem are equivalent.

3. Declaring namespaces: the @namespace rule

The @namespace at-rule declares a namespace prefix and associates it with a given namespace name (a string). This namespace prefix can then be used in namespace-qualified names such as the CSS qualified names defined below.

@namespace "http://www.w3.org/1999/xhtml";
@namespace svg "http://www.w3.org/2000/svg";

The first rule declares a default namespace http://www.w3.org/1999/xhtml to be applied to names that have no explicit namespace component.

The second rule declares a namespace prefix svg that is used to apply the namespace http://www.w3.org/2000/svg where the svg namespace prefix is used.

In CSS Namespaces, as in Namespaces in XML 1.0, the prefix is merely a syntactic construct; it is the expanded name (the tuple of local name and namespace name) that is significant. Thus the actual prefixes used in a CSS style sheet, and whether they are defaulted or not, are independent of the namespace prefixes used in the markup and whether these are defaulted or not.

For example, given the following XML document:

<qml:elem xmlns:qml="http://example.com/q-markup"></qml:elem>

and the following @namespace declarations at the beginning of a CSS file:

@namespace Q "http://example.com/q-markup";
@namespace lq "http://example.com/q-markup";

The selectors Q|elem and lq|elem in that CSS file would both match the element <qml:elem>. (The selector qml|elem would be invalid.)

3.1 Syntax

The syntax for the @namespace rule is as follows (using the notation from the Grammar appendix of CSS 2.1 [CSS21]):

namespace
  : NAMESPACE_SYM S* [namespace_prefix S*]? [STRING|URI] S* ';' S*
  ;
namespace_prefix
  : IDENT
  ;

with the new token:

@{N}{A}{M}{E}{S}{P}{A}{C}{E} {return NAMESPACE_SYM;}

Any @namespace rules must follow all @charset and @import rules and precede all other non-ignored at-rules and rule sets in a style sheet. For CSS syntax this adds [ namespace [S|CDO|CDC]* ]* immediately after [ import [S|CDO|CDC]* ]* in the stylesheet grammar.

A syntactically invalid @namespace rule (whether malformed or misplaced) must be ignored. A CSS style sheet containing an invalid @namespace rule is itself invalid.

A URI string parsed from the URI syntax must be treated as a literal string: as with the STRING syntax, no URI-specific normalization is applied.

All strings—including the empty string and strings representing invalid URIs—are valid namespace names in @namespace declarations.

3.2 Scope

The namespace prefix is declared only within the style sheet in which its @namespace rule appears. It is not declared in any style sheets importing or imported by that style sheet, nor in any other style sheets applying to the document.

3.3 Declaring Prefixes

A namespace prefix, once declared, represents the namespace for which it was declared and can be used to indicate the namespace of a namespace-qualified name. Namespace prefixes are, like CSS counter names, case-sensitive.

If in the namespace declaration the namespace prefix is omitted, then the namespace so declared is the default namespace. The default namespace may apply to names that have no explicit namespace prefix: modules that employ namespace prefixes must define in which contexts the default namespace applies. For example, following [XML-NAMES], in Selectors [SELECT] the default namespace applies to type selectors—but it does not apply to attribute selectors. There is no default value for the default namespace: modules that assign unqualified names to the default namespace must define how those unqualified names are to be interpreted when no default namespace is declared.

Note that using default namespaces in conjunction with type selectors can cause UAs that support default namespaces and UAs that don't support default namespaces to interpret selectors differently. See Namespaces and down-level clients in the Selectors module [SELECT] for details.

If a namespace prefix or default namespace is declared more than once only the last declaration shall be used.

4. CSS Qualified Names

A CSS qualified name is a name explicitly located within (associated with) a namespace. To form a qualified name in CSS syntax, a namespace prefix that has been declared within scope is prepended to a local name (such as an element or attribute name), separated by a "vertical bar" (|, U+007C). The prefix, representing the namespace for which it has been declared, indicates the namespace of the local name. The prefix of a qualified name may be omitted to indicate that the name belongs to no namespace, i.e. that the namespace name part of the expanded name has no value. Some contexts (as defined by the host language) may allow the use of an asterisk (*, U+002A) as a wildcard prefix to indicate a name in any namespace, including no namespace.

Given the namespace declarations:

@namespace toto "http://toto.example.org";
@namespace "http://example.com/foo";

In a context where the default namespace applies

toto|A
represents the name A in the http://toto.example.org namespace.
|B
represents the name B that belongs to no namespace.
*|C
represents the name C in any namespace, including no namespace.
D
represents the name D in the http://example.com/foo namespace.

The syntax for the portion of a CSS qualified name before the local name is given below, both for qualified names that allow wildcard prefixes (wqname) and for qualified names that disallow wildcard prefixes (qname). (The syntax uses notation from the Grammar appendix of CSS 2.1 [CSS21]):

qname_prefix
  : [namespace_prefix]? '|'
  ;
wqname_prefix
  : namespace_prefix? '|'
  | '*' '|'
  ;

CSS qualified names can be used in (for example) selectors and property values as described in other modules. Those modules must define handling of namespace prefixes that have not been properly declared. Such handling should treat undeclared namespace prefixes as a parsing error that will cause the selector or declaration (etc.) to be considered invalid and, in CSS, ignored.

For example, the Selectors module [SELECT] defines a type selector with an undeclared namespace prefix to be an invalid selector, and CSS [CSS21] requires rule sets with an invalid selector to be completely ignored.

Acknowledgments

This draft borrows heavily from earlier drafts on CSS namespace support by Chris Lilley and by Peter Linss and early (unpublished) drafts on CSS and XML by Håkon Lie and Bert Bos, and XML Namespaces and CSS by Bert Bos and Steven Pemberton. Many current and former members of the CSS Working Group have contributed to this document. Discussions on www-style@w3.org and in other places have also contributed ideas to this specification. Special thanks goes to L. David Baron, Karl Dubost, Ian Hickson, Bjöern Höhrmann, and Lachlan Hunt for their comments.

References

Normative references

[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 19 July 2007. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2007/CR-CSS21-20070719
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[XML-NAMES]
Tim Bray; et al. Namespaces in XML 1.0 (Second Edition). 16 August 2006. W3C Recommendation. URL: http://www.w3.org/TR/2006/REC-xml-names-20060816

Informative references

[SELECT]
Daniel Glazman; Tantek Çelik; Ian Hickson. Selectors. 15 December 2005. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2005/WD-css3-selectors-20051215


CSS3 Ruby Module

W3C Candidate Recommendation 14 May 2003

This version:
http://www.w3.org/TR/2003/CR-css3-ruby-20030514
Latest version:
http://www.w3.org/TR/css3-ruby
Previous version:
http://www.w3.org/TR/2002/WD-css3-ruby-20021024
Editor:
Michel Suignard (Microsoft)
Contributors:
Marcin Sawicki (former editor) (Microsoft)
Michel Suignard (Microsoft)

Copyright © 2003 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.

Abstract

"Ruby" are short runs of text alongside the base text, typically used in East Asian documents to indicate pronunciation or to provide a short annotation. This document proposes a set of CSS properties associated with the 'Ruby' elements. They can be used in combination with the Ruby elements of HTML [RUBY].

Status of This Document

This specification is one of the "modules" for the upcoming CSS level 3 (CSS3) specification. It has been developed by the CSS Working Group which is part of the Style activity (see summary). It contains features to be included in CSS level 3.

This is a Candidate Recommendation, which means W3C believes the specification is ready to be implemented.

All persons are encouraged to review and implement this specification and send comments to the (archived) public mailing list www-style (see instructions). W3C Members can also send comments directly to the CSS Working Group.

For this specification to become a W3C Recommendation, the following criteria must be met:

  1. There must be at least two interoperable implementations for every feature in the specification.

    For the purposes of this criterion, we define the following terms:

    feature
    a section or subsection in the specification
    interoperable
    passing the respective test case(s) in the test suite, or, if the implementation is not a web browser, an equivalent test. Every relevant test in the test suite should have an equivalent test created if such a user agent (UA) is to be used to claim interoperability. In addition if such a UA is to be used to claim interoperability, then there must one or more additional UAs which can also pass those equivalent tests in the same way for the purpose of interoperability. The equivalent tests must be made publically available for the purposes of peer review.
    implementation
    a user agent which:
    1. implements the feature.
    2. is available (i.e. publicly downloadable or available through some other public point of sale mechanism). This is the "show me" requirement.
    3. is shipping (i.e. development, private or unofficial versions are insufficient).
    4. is not experimental (i.e. is intended for a wide audience and could be used on a daily basis.)
  2. A minimum of six months of the CR period must have elapsed. This is to ensure that enough time is given for any remaining major errors to be caught.

The comments that the CSS WG received on the last working draft, together with responses and resulting changes are listed in the disposition of comments.

Patent disclosures relevant to CSS may be found on the Working Group's public patent disclosure page.

To find the latest version of this specification, please follow the "Latest version" link above, or visit the list of W3C Technical Reports.

Contents

  • 1. Dependencies
  • 2. Introduction
    • 2.1 Document conventions
    • 2.2 What is ruby?
  • 3. The CSS ruby model
    • 3.1 Ruby specific 'display' property values
    • 3.2 Ruby box model
    • 3.3 Ruby box and line stacking
  • 4. Ruby Properties
    • 4.1 Ruby positioning: the 'ruby-position' property
    • 4.2 Ruby alignment: the 'ruby-align' property
    • 4.3 Ruby overhanging: the 'ruby-overhang' property
    • 4.4 Ruby annotation spanning: the 'ruby-span' property
  • 5. Properties index
  • 6. Profiles
  • Glossary
  • Acknowledgements
  • References

1. Dependencies on other modules

This CSS3 module depends on the following other CSS3 modules:

  • Text
  • Line
  • Syntax
  • Values and units

2. Introduction

2.1 Document conventions

There is a number of illustrations in this document for which the following legend is used:

Symbolic wide-cell glyph representation - wide-cell glyph (e.g. Han) which is the n-th character in the text run, they may also appear as half size boxes when used as annotations.
Symbolic narrow-cell glyph representation - narrow-cell glyph (e.g. Roman) which is the n-th glyph in the text run.

Many typographical properties in East Asian typography depend on the fact that a character is typically rendered as either a wide or narrow character. All characters described by the Unicode Standard [UNICODE] can be categorized by a width property. This is covered by the Unicode Standard Annex [UAX#11].

The orientation which the above symbols assume in the diagrams corresponds to the orientation that the glyphs they represent are intended to assume when rendered by the user agent. Spacing between these characters in the diagrams is usually symbolic, unless intentionally changed to make a point.

Finally, in this document, requirements are expressed using the key words "MUST", "MUST NOT", "REQUIRED", "SHALL" and "SHALL NOT". Recommendations are expressed using the key words "SHOULD", "SHOULD NOT" and "RECOMMENDED". "MAY" and "OPTIONAL" are used to indicate optional features or behavior. These keywords are used in accordance with [RFC 2119]. For legibility these keywords are used in lowercase form.

2.2 What is ruby?

"Ruby" is the commonly used name for a run of text that appears in the immediate vicinity of another run of text, referred to as the "base", and serves as an annotation or a pronunciation guide associated with that run of text. Ruby, as used in Japanese, is described in JIS X-4051 [JIS4051]. The ruby structure and the XHTML markup to represent it is described in the Ruby Annotation [RUBY]. This section describes the CSS properties relevant to ruby. The following figures show two examples of Ruby.

Example of ruby applied on top of a Japanese expression

Figure 2.2.1: Example of ruby used in Japanese (simple case)

Example showing complex ruby with annotation text before and after the base characters

Figure 2.2.2: Complex ruby with annotation text before and after the base characters

In the first example, a single annotation is used to annotate the base sequence. In Japanese typography, this simple case is sometimes called "taigo ruby" (per-word ruby).

In the second example, multiple annotations are attached to a base sequence, the hiragana characters on top refer to the pronunciation of each of the base Kanji characters (annotated in a monoruby fashion), while the words 'Keio' and 'University' on the bottom are annotations describing the English translation of respectively the first four and the last two Kanji characters of the base. To allow correct association between the hiragana characters and their corresponding Kanji base characters, the spacing between these Kanji characters may be adjusted (this happens to the fourth Kanji character in the figure 2.1.2 above).

Note: To avoid variable spacing between the Kanji characters in the example above the hiragana annotations can also be created as a simple annotation ruby.

The two examples correspond respectively to two types of ruby: a simple ruby using a simple ruby markup and a complex ruby using a complex ruby markup.

3. The CSS ruby model

3.1 Ruby specific 'display' property values

The CSS ruby model is based on the W3C Ruby Annotation Recommendation [RUBY], which is consistent with the XHTML Modularization Framework [XHTMLMOD]. The Recommendation specifies the ruby structure in a way to closely parallel the visual layout of the ruby element. In this model, a ruby consists of one or more base elements associated with one or more annotation elements.

The CSS model does not require that the document language include elements that correspond to each of these components. For document languages (such as XML applications) that do not have pre-defined ruby elements, authors must map document language elements to ruby elements; this is done with the 'display' property. The following 'display' values assign ruby semantics to an arbitrary element:

ruby (in XHTML: ruby)
Specifies that an element defines a ruby structure.
ruby-base (in XHTML: rb)
Specifies that an element defines a ruby base.
ruby-text (in XHTML: rt)
Specifies that an element defines a ruby text.
ruby-base-container (in XHTML: rbc)
Specifies that an element contains one or more ruby base.
ruby-text-container (in XHTML: rtc)
Specifies that an element contains one or more ruby text.

The rbspan attribute should also be used by XML applications to allow annotation spanning; but in addition, the 'ruby-span' property must be used by those applications to indicate to the user agent the number of ruby base elements to be spanned.

3.2 Ruby box model

In the following description, the elements specified by the Ruby Annotation [RUBY] are used to describe the box model. As mentioned earlier, a user agent can obtain the same results by using the Ruby specific 'display' property values.

For a user agent that supports the ruby markup, the ruby structure consists of three or more boxes. The outermost container is the ruby element itself. In the simple case, it is a container for two non-overlapping boxes: the ruby text box (rt element) and the ruby base box (rb element). The positioning of these two boxes relative to each other is controlled by the 'ruby-position' property.

Diagram of the ruby box model consisting of two boxes, one on top of the other, enclosed within a third box representing the ruby element

Figure 3.2.1: Ruby box model (simple case)

In the case of complex ruby, the ruby element is a container for two or three non-overlapping boxes: one ruby base collection (rbc element), and one or two ruby text collections (rtc element). The rbc element is itself a container for one or several ruby base box (rb element), while each rtc element is a container for one or several ruby text box (rt element). The position of the rtc element in relation to the related rbc element is controlled by the 'ruby-position' property. The two following figures show examples of these complex ruby.

Diagram of a group ruby with a full ruby text above and partial ruby text below

Figure 3.2.2: Ruby box model (complex ruby with an empty rt element after)

In the example above, the ruby text after (below) the ruby bases contains two rt elements with the first one being empty, the empty rt element corresponds to the first part of the ruby base collection (the first part is identified by the first rb element within the rbc element).

Diagram of a group ruby with a spanning ruby text above and partial ruby text below

Figure 3.2.3: Ruby box model (complex ruby with a spanning ruby text element)

In the example above, the ruby text before (above) the ruby bases spans the whole ruby base collection. The ruby text after (below) the ruby bases still contain two rt elements, one of which is empty. The spanning behavior of rt text elements is controlled by the rbspan attribute in a way similar to the colspan attribute used for table column.

Note: The visual description of the ruby elements does not refer necessarily to the logical orders of the elements

The width of the ruby box is by default determined by its widest child element, whose width in turn is determined by its content. The width of all direct children of the ruby element is the width of the widest children. In this respect, the ruby box is much like a two or three row table element, with the following exceptions:

  • the ruby box is an inline element, like an image, even though it itself, like a table, is a container of other boxes
  • the equivalent of the cells: the rb element and the rt text element can only contain inline-level elements.
  • the content of each 'cell' is always measured at its maximum width
  • unlike a table, a ruby element doesn't have to fit in a line, the ruby box may be split into several boxes at line boundary, depending of the spanning of the ruby texts. This is however only possible for the complex ruby and can only happen at the boundary of non spanning elements.
  • both the ruby text and the ruby base boxes may overlap with adjacent text (outside of the ruby element) if an appropriate 'ruby-overhang' parameter is set via CSS. Note however that the actual content of the ruby base cannot overlap with that adjacent text. The distribution of the content of the ruby base within the ruby base box is controlled by the 'ruby-align' property.

If the ruby text is not allowed to overhang, then the ruby behaves like a traditional box, i.e. only its contents are rendered within its boundaries and adjacent elements do not cross the box boundary:

Diagram showing the ruby boxes interacting with adjacent text

Figure 3.2.4: Simple ruby whose text is not allowed to overhang adjacent text

However, if ruby text is allowed to overhang adjacent elements and it happens to be wider than its base, then the adjacent content is partially rendered within the area of the ruby base box, while the ruby text may be partially overlapping with the upper blank parts of the adjacent content:

Diagram showing the ruby boxes interacting with adjacent text

Figure 3.2.5: Simple ruby whose text is allowed to overhang adjacent text

The ruby text related to a ruby base can never overhang another ruby base.

POWERED BY HeroNote

The alignment of the contents of the base or the ruby text is not affected by the overhanging behavior. The alignment is achieved the same way regardless of the overhang behavior setting and it is computed before the space available for overlap is determined. It is controlled by the 'ruby-align' property.

The exact circumstances in which the ruby text will overhang other elements, and to what degree it will do so, will be controlled by the 'ruby-overhang' property.

This entire logic applies the same way in vertical ideographic layout, only the dimension in which it works in such a layout is vertical, instead of horizontal.

Note: Because the purpose of the XHTML rp element [RUBY] is to allow pre-existing user agents to parenthesize ruby text content, an XHTML user agent should use a styling rule for these elements that avoids rendering them such as rp {display: none}.

3.3 Ruby box and line stacking

The interaction of the ruby box and line stacking is controlled by the 'line-stacking-ruby' property described in the CSS3 Line Module. That property takes two values: 'include-ruby' and 'exclude-ruby. Depending on the property value, the ruby box is considered or excluded for line stacking. Even if the ruby box is considered for line stacking, some values of the 'line-stacking-strategy' property (also described in the CSS3 Line module) can still create occurrences where a the ruby box will eventually be ignored (e.g. case where the 'line-stacking-strategy' value is 'block-line-height').

In the following figure, each line box is shown with leading space distributed before and after the two text segments ('Previous line' and 'Ruby base'); the dotted lines show the line box for each line. The 'line-stacking-ruby' property is set to 'exclude-ruby'. The achieved effect is that the ruby box does not affect the line to line spacing. It is however the responsibility of the style author to avoid 'bleeding' effects between the ruby text and the surrounding text of images.

Diagram showing the ruby text using 2 half leading

Figure 3.3.1: Excluded Ruby text

In the following figure, the line boxes have no extra leading space. The 'line-stacking-ruby' property is set to 'include-ruby' and the 'line-stacking-strategy' property is set to a value where inline boxes are considered for line stacking. In this case, the line box with the ruby text is affected and has its 'stack-height' increased by the amount necessary to fit the ruby text.

Diagram showing the ruby text expanding above base text

Figure 3.3.2: Ruby text increasing line height

This mechanism allows rendering of evenly spaced lines of text within a block-level element, whether a line contains ruby or not. The authors need only to set for the block-level element a line height value larger than the computed line-height of the largest ruby element within the block.

4. Ruby Properties

All properties, in addition to the noted values, take 'initial' and 'inherit'. These values are not repeated in each of the property value enumeration.

4.1 Ruby positioning: the 'ruby-position' property

Name: | 'ruby-position'
Value: | before | after | right
Initial: | before
Applies to: | the parent of elements with display: ruby-text.
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value (except for initial and inherit)

This property is used by the parent of elements with display: ruby-text to control the position of the ruby text with respect to its base. Such parents are typically either the ruby element itself (simple ruby) or the rtc element (complex ruby). This assures that all part of a rtc element will be displayed in the same position. Possible values:

before
The ruby text appears before the base. This is the most common setting used in ideographic East Asian writing systems. This is the initial value.

Diagram of ruby glyph layout in horizontal mode with ruby text appearing above the base

Figure 4.1.1: Top ruby in horizontal layout applied to Japanese text

If the base appears in a vertical-ideographic layout mode, the ruby appears on the right side of the base and is rendered in the same layout mode as the base (i.e. vertical-ideographic).

Diagram of ruby glyph layout in vertical mode with ruby text apearing vertically on the right of the base

Figure 4.1.2: Top ruby in vertical ideographic layout applied to Japanese text

Note the special case of traditional Chinese as used especially in Taiwan: ruby (made of Bopomofo glyphs) in that context can appear along the right side of the base glyph, as if the text were in vertical layout, but the bases themselves are rendered on a horizontal line, since the actual layout is horizontal:

Example of Taiwanese-style ruby

Figure 4.1.3: "Bopomofo" ruby in traditional Chinese (ruby text shown in blue for clarity) in horizontal layout

In order to achieve that effect, vertical-ideographic layout should be set on each individual ruby. That can be accomplished with the following simple CSS rule:

ruby.bopomofo { writing-mode: tb-rl }

Note: The Bopomofo transcription is written in the normal way as part of the ruby text. The user agent is responsible for ensuring the correct relative alignment and positioning of the glyphs, including those corresponding to the tone marks, when displaying as vertical ruby.

after
The ruby text appears after the base. This is a relatively rare setting used in ideographic East Asian writing systems, most easily found in educational text.

Diagram of ruby glyph layout in horizontal mode with ruby text appearing below the base

Figure 4.1.4: Bottom ruby in horizontal layout applied to Japanese text

If the base appears in a vertical ideographic mode, the bottom ruby appears on the left side of the base and is rendered in the same layout mode as the base (i.e. vertical).

Diagram of ruby glyph layout in vertical mode with ruby text apearing vertically on the left of the base

Figure 4.1.5: Bottom ruby in vertical ideographic layout applied to Japanese text

right
The ruby text appears on the right of the base. Unlike 'before' and 'after', this value is not relative to the text flow direction.

If two rtc elements are set with the same ruby-position value, (for example both 'before'), the relative position of the two elements is undefined. This setting should not be used.

4.2 Ruby alignment: the 'ruby-align' property

Name: | 'ruby-align'
Value: | auto | start | left | center | end | right | distribute-letter | distribute-space | line-edge
Initial: | auto
Applies to: | all elements and generated content
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value (except for initial and inherit)

This property can be used on any element to control the text alignment of the ruby text and ruby base contents relative to each other. It applies to all the ruby's in the element. For simple ruby, the alignment is applied to the ruby child element whose content is shorter: either the rb element or the rt element [RUBY]. For complex ruby, the alignment is also applied to the ruby child elements whose content is shorter: either the rb element and/or one or two rt elements for each related ruby text and ruby base element within the rtc and rbc element.

Possible values:

auto
The user agent determines how the ruby contents are aligned. This is the initial value. The behavior recommended by [JIS4051] is for a wide-cell ruby is to be aligned in the 'distribute-space' mode:

Diagram of glyph layout in auto aligned ruby when ruby text is shorter than base Diagram of glyph layout in auto aligned ruby when ruby text is longer than base

Figure 4.2.1: Wide-cell text in 'auto' ruby alignment is 'distribute-space' justified

The recommended behavior for a narrow-cell glyph ruby is to be aligned in the 'center' mode.

Diagram of glyph layout in auto aligned ruby when halfwidth ruby text is shorter than base Diagram of character layout in auto aligned ruby when ruby text is longer than narrow-width base

Figure 4.2.2: Narrow-width ruby text in 'auto' ruby alignment is centered

start
left
The ruby text content is aligned with the start edge of the base.

Diagram of glyph layout in left aligned ruby when ruby text is shorter than base Diagram of glyph layout in left aligned ruby when ruby text is longer than base

Figure 4.2.3: Start ruby alignment

center
The ruby text content is centered within the width of the base. If the length of the base is smaller than the length of the ruby text, then the base is centered within the width of the ruby text.

Diagram of glyph layout in center aligned ruby when ruby text is shorter than base Diagram of glyph layout in center aligned ruby when ruby text is longer than base

Figure 4.2.4: Center ruby alignment

end
right
The ruby text content is aligned with the end edge of the base.

Diagram of glyph layout in right aligned ruby when ruby text is shorter than base Diagram of glyph layout in right aligned ruby when ruby text is longer than base

Figure 4.2.5: End ruby alignment

distribute-letter
If the width of the ruby text is smaller than that of the base, then the ruby text contents are evenly distributed across the width of the base, with the first and last ruby text glyphs lining up with the corresponding first and last base glyphs. If the width of the ruby text is at least the width of the base, then the letters of the base are evenly distributed across the width of the ruby text.

Diagram of glyph layout in distribute-letter aligned ruby when ruby text is shorter than base Diagram of glyph layout in distribute-letter aligned ruby when ruby text is longer than base

Figure 4.2.6: Distribute-letter ruby alignment

distribute-space
If the width of the ruby text is smaller than that of the base, then the ruby text contents are evenly distributed across the width of the base, with a certain amount of white space preceding the first and following the last character in the ruby text. That amount of white space is normally equal to half the amount of inter-character space of the ruby text. If the width of the ruby text is at least the width of the base, then the same type of space distribution applies to the base. In other words, if the base is shorter than the ruby text, the base is distribute-space aligned. This type of alignment is sometimes referred to as the "1:2:1" alignment [JIS4051].

Diagram of glyph layout in distribute-space aligned ruby when ruby text is shorter than base Diagram of glyph layout in distribute-space aligned ruby when ruby text is longer than base

Figure 4.2.7: Distribute-space ruby alignment

line-edge
If the ruby text is not adjacent to a line edge, it is aligned as in 'auto'. If it is adjacent to a line edge, then it is still aligned as in auto, but the side of the ruby text that touches the end of the line is lined up with the corresponding edge of the base. This type of alignment is specified by [JIS4051]. This type of alignment is relevant only to the scenario where the ruby text is longer than the ruby base. In the other scenarios, this is just 'auto'.

Diagram of glyph layout in line-edge aligned ruby when ruby text is shorter than base Diagram of glyph layout in line-edge aligned ruby when ruby text is longer than base

Figure 4.2.8: Line edge ruby alignment

For a complex ruby with spanning elements, one additional consideration is required. If the spanning element spans multiple 'rows' (other rbc or rtc elements), and the ruby alignment requires space distribution among the 'spanned' elements, a ratio must be determined among the 'columns' of spanned elements. This ratio is computed by taking into consideration the widest element within each column.

In the context of this property, the 'left' and 'right' values are synonymous with the 'start' and 'end' values respectively. I.e. their meaning is relative according to the text layout flow. Most of the other CSS properties interpret 'left' and 'right' on an 'absolute' term. See Appendix A of the CSS3 Text Module for further details.

4.3 Ruby overhanging: the 'ruby-overhang' property

Name: | 'ruby-overhang'
Value: | auto | start | end | none
Initial: | none
Applies to: | the parent of elements with display: ruby-text
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value (except for initial and inherit)

This property determines whether, and on which side, ruby text is allowed to partially overhang any adjacent text in addition to its own base, when the ruby text is wider than the ruby base. Note that ruby text is never allowed to overhang glyphs belonging to another ruby base. Also the user agent is free to assume a maximum amount by which ruby text may overhang adjacent text. The user agent may use the [JIS4051] recommendation of using one ruby text character length as the maximum overhang length.

Possible values:

auto
The ruby text can overhang text adjacent to the base on either side. [JIS4051] specifies the categories of characters that ruby text can overhang. The user agent is free to follow the [JIS4051] recommendation or specify its own classes of characters to overhang. This is the initial value.

Diagram of glyph layout in overhanging ruby

Figure 4.3.1: Ruby overhanging adjacent text

start
The ruby text can overhang the text that precedes it. That means, for example, that ruby can overhang text that is to the left of it in horizontal LTR layout, or it can overhang text that is above it in vertical-ideographic layout.

Diagram of glyph layout when ruby overhangs the preceding glyphs only

Figure 4.3.2: Ruby overhanging preceding text only

end
The ruby text can overhang the text that follows it. That means, for example, that ruby can overhang text that is to the right of it in horizontal LTR layout, or it can overhang text that is below it in vertical-ideographic layout.

Diagram of glyph layout when ruby overhangs the following characters only

Figure 4.3.3: Ruby overhanging following text only

none
The ruby text cannot overhang any text adjacent to its base, only its own base.

Diagram of glyph layout in non-overhanging ruby

Figure 4.3.4: Ruby not allowed to overhang adjacent text

4.4 Ruby annotation spanning: the 'ruby-span' property

Name: | 'ruby-span'
Value: | attr(x) | none
Initial: | none
Applies to: | elements with display: ruby-text
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | <number>

This property controls the spanning behavior of annotation elements.

Note: A XHTML user agent may also use the rbspan attribute to get the same effect.

Possible values:

attr(x)
The value of attribute 'x' as a string value. The string value is evaluated as a <number> to determine the number of ruby base elements to be spanned by the annotation element. If the <number> is '0', it is replaced by '1'.The <number> is the computed value.
none
No spanning. The computed value is '1'.

The following example shows an XML example using the 'display' property values associated with the 'ruby structure and the 'ruby-span' property

myruby       { display: ruby-base; }
myrbc        { display: ruby-base-container; }
myrb         { display: ruby-base; }
myrtc.before { display: ruby-text-container; ruby-position: before}
myrtc.after  { display: ruby-text-container; ruby-position: after}
myrt         { display: ruby-text; ruby-span: attr(rbspan); }
...
<myruby>
  <myrbc>
    <myrb>10</myrb>
    <myrb>31</myrb>
    <myrb>2002</myrb>
  </myrbc>
  <myrtc class="before">
    <myrt>Month</myrt>
    <myrt>Day</myrt>
    <myrt>Year</myrt>
  </myrtc>
  <myrtc class="after">
    <myrt rbspan="3">Expiration Date</myrt>
  </myrtc>
</myruby>

5. Properties index

In addition to the specified values, all properties take the 'inherit' and 'initial' values.

Name | Values | Initial | Applies to | Inh. | Percentages | Media groups
'ruby-align' | auto | start | left | center | end | right | distribute-letter | distribute-space | line-edge | auto | all elements and generated content | yes | N/A | visual
'ruby-overhang' | auto | start | end | none | none | the parent of elements with display: ruby-text | yes | N/A | visual
'ruby-position' | before | after | right | inline | see individual properties | the parent of elements with display: ruby-text | yes | N/A | visual
'ruby-span' | attr(x) | none | none | elements with display: ruby-text | no | N/A | visual

6. Profiles

There are two modules defined by this chapter:

CSS3 Simple Ruby model

CSS3 Complex Ruby model.

They both contain all the properties specified by this CSS chapter, i.e. 'ruby-align', 'ruby-overhang', 'ruby-position' and 'ruby-span'. They differ by the required 'display' property values. The Simple Ruby model requires the values: 'ruby', 'ruby-base' and 'ruby-text'. The Complex Ruby model requires in addition the values: 'ruby-base-container' and 'ruby-text-container'.

Glossary

Bopomofo
37 characters and 4 tone markings used as phonetics in Chinese, especially standard Mandarin.
Hanja
Subset of the Korean writing system that utilizes ideographic characters borrowed or adapted from the Chinese writing system. Also see Kanji.
Hiragana
Japanese syllabic script, or character of that script. Rounded and cursive in appearance. Subset of the Japanese writing system, used together with kanji and katakana. In recent times, mostly used to write Japanese words when kanji are not available or appropriate, and word endings and particles. Also see Katakana.
Ideograph
A character that is used to represent an idea, word, or word component, in contrast to a character from an alphabetic or syllabic script. The most well-known ideographic script is used (with some variation) in East Asia (China, Japan, Korea,...).
Kana
Collective term for hiragana and katakana.
Kanji
Japanese term for ideographs; ideographs used in Japanese. Subset of the Japanese writing system, used together with hiragana and katakana. Also see Hanja.
Katakana
Japanese syllabic script, or character of that script. Angular in appearance. Subset of the Japanese writing system, used together with kanji and hiragana. In recent times, mainly used to write foreign words. Also see Hiragana.
Monoruby
In Japanese typography: Ruby associated with a single character of the base text.
Ruby
A run of text that appears in the vicinity of another run of text and serves as an annotation or a pronunciation guide for that text.

Acknowledgements

This specification would not have been possible without the help from:

Stephen Deach, Martin Dürst, Hideki Hiura(樋浦 秀樹), Masayasu Ishikawa(石川 雅康), Chris Pratley, Takao Suzuki(鈴木 孝雄), Frank Yung-Fong Tang, Chris Thrasher, Masafumi Yabe家辺 勝文), Steve Zilles.

References

[CSS2]
Cascading Stylesheets, level 2 (CSS2) Specification, W3C Recommendation
Bert Bos, Håkon Wium Lie, Chris Lilley and Ian Jacobs, 12 May 1998
Available at: http://www.w3.org/TR/1998/REC-CSS2-19980512
[CSS3TEXT]
CSS3 module: Text (working draft)
Michel Suignard; 24 October 2002
Available at: http://www.w3.org/TR/2002/WD-css3-text-20021024
[HTML4]
HTML 4.01 Specification, W3C Recommendation
Dave Raggett, Arnaud Le Hors and Ian Jacobs, 18 December 1997, latest revised 24 December 1999
Available at: http://www.w3.org/TR/1999/REC-html401-19991224
[JIS4051]
Line composition rules for Japanese documents (日本語文書の行組版方法)
JIS X 4051-1995, Japanese Standards Association, 1995 (in Japanese)
[JIS4052]
"Exchange format for Japanese documents with composition markup" (日本語文書の組版指定交換形式)
JIS X 4052:2000, Japanese Standards Association, 2000 (in Japanese)
[RFC 2119]
Scott Bradner, Key words for use in RFCs to Indicate Requirement Levels, IETF RFC 2119.
(See http://www.ietf.org/rfc/rfc2119.txt.)
[RUBY]
Ruby Annotation, W3C Recommendation
Marcin Sawicki, Michel Suignard, Masayasu Ishikawa, Martin Dürst and Tex Texin, 31 May 2001,
Available at: http://www.w3.org/TR/2001/REC-ruby-20010531/
[UNICODE]
The Unicode Consortium. Book version: The Unicode Standard: Version 3.0. Addison Wesley Longman. 2000. ISBN 0-201-61633-5. Online version: The Unicode Standard: Version 3.2.0, URL:
http://www.unicode.org/unicode/standard/versions/enumeratedversions.html#Unicode_3_2_0
For more information, consult the Unicode Consortium's home page at http://www.unicode.org/
[UAX#11]
Asmus Freytag. East Asian Width. 15 March 2002. Unicode Standard Annex #11. URL:
http://www.unicode.org/unicode/reports/tr11/tr11-10.html
[XSL]
Extensible Stylesheet Language (XSL) Version 1.0, W3C Recommendation
Sharon Adler, Stephen Deach, et al., 15 October 2001
Available at: http://www.w3.org/TR/2001/REC-xsl-20011015/
[XHTMLMOD]
Modularization of XHTML, W3C Recommendation
Murray Altheim, Shane McCarron, et al., 10 April 2001
Available at: http://www.w3.org/TR/2001/REC-xhtml-modularization-20010410/


CSS3 Selectors

Selectors Level 3

W3C Proposed Recommendation 15 December 2009

This version:
http://www.w3.org/TR/2009/PR-css3-selectors-20091215
Latest version:
http://www.w3.org/TR/css3-selectors
Previous version:
http://www.w3.org/TR/2009/WD-css3-selectors-20090310
Editors:
Tantek Çelik (Invited Expert)
Elika J. Etemad (Invited Expert)
Daniel Glazman (Disruptive Innovations SARL)
Ian Hickson (Google)
Peter Linss (former editor, Netscape/AOL)
John Williams (former editor, Quark, Inc.)

Copyright © 2009 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

Selectors are patterns that match against elements in a tree, and as such form one of several technologies that can be used to select nodes in an XML document. Selectors have been optimized for use with HTML and XML, and are designed to be usable in performance-critical code.

CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and XML documents on screen, on paper, in speech, etc. CSS uses Selectors for binding style properties to elements in the document.

This document describes the selectors that already exist in CSS1 [CSS1] and CSS2 [CSS21], and further introduces new selectors for CSS3 and other languages that may need them.

Selectors define the following function:

expression ∗ element → boolean

That is, given an element and a selector, this specification defines whether that element matches the selector.

These expressions can also be used, for instance, to select a set of elements, or a single element from a set of elements, by evaluating the expression across all the elements in a subtree. STTS (Simple Tree Transformation Sheets), a language for transforming XML trees, uses this mechanism. [STTS3]

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document was produced by the CSS Working Group as a Proposed Recommendation.

A Proposed Recommendation is a specification that is under review by the W3C Advisory Committee for endorsement as a W3C Recommendation. It is is a mature document that has been widely reviewed and has been shown to be implementable. W3C encourages everybody to implement this specification. Comments may be sent to the (archived) public mailing list www-style@w3.org (see instructions). When sending e-mail, please put the text “css3-selectors” in the subject, preferably like this: “[css3-selectors] …summary of comment…”

Publication as a Proposed Recommendation does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

A separate implementation report contains a test suite and shows several implementations of the specification.

The list of comments on the last draft explains the changes that were made since that draft.

The bibliography contains normative references to two W3C specifications that are not Recommendations at the time of publication, although they are believed to be stable. It is currently the intention to keep this specification at Proposed Recommendation level until those specifications are themselves Proposed Recommendations or Recommendations.

Advisory Committee representatives of W3C member organizations are requested to fill in the review form before 31 January 2010.

Table of contents

  • 1. Introduction
    • 1.1. Dependencies
    • 1.2. Terminology
    • 1.3. Changes from CSS2
  • 2. Selectors
  • 3. Case sensitivity
  • 4. Selector syntax
  • 5. Groups of selectors
  • 6. Simple selectors
    • 6.1. Type selector
      • 6.1.1. Type selectors and namespaces
    • 6.2. Universal selector
      • 6.2.1. Universal selector and namespaces
    • 6.3. Attribute selectors
      • 6.3.1. Attribute presence and value selectors
      • 6.3.2. Substring matching attribute selectors
      • 6.3.3. Attribute selectors and namespaces
      • 6.3.4. Default attribute values in DTDs
    • 6.4. Class selectors
    • 6.5. ID selectors
    • 6.6. Pseudo-classes
      • 6.6.1. Dynamic pseudo-classes
        • 6.6.1.1. The link pseudo-classes: :link and :visited
        • 6.6.1.2. The user action pseudo-classes :hover, :active, and :focus
      • 6.6.2. The target pseudo-class :target
      • 6.6.3. The language pseudo-class :lang
      • 6.6.4. The UI element states pseudo-classes
        • 6.6.4.1. The :enabled and :disabled pseudo-classes
        • 6.6.4.2. The :checked pseudo-class
        • 6.6.4.3. The :indeterminate pseudo-class
      • 6.6.5. Structural pseudo-classes
        • 6.6.5.1. :root pseudo-class
        • 6.6.5.2. :nth-child() pseudo-class
        • 6.6.5.3. :nth-last-child() pseudo-class
        • 6.6.5.4. :nth-of-type() pseudo-class
        • 6.6.5.5. :nth-last-of-type() pseudo-class
        • 6.6.5.6. :first-child pseudo-class
        • 6.6.5.7. :last-child pseudo-class
        • 6.6.5.8. :first-of-type pseudo-class
        • 6.6.5.9. :last-of-type pseudo-class
        • 6.6.5.10. :only-child pseudo-class
        • 6.6.5.11. :only-of-type pseudo-class
        • 6.6.5.12. :empty pseudo-class
      • 6.6.6. Blank
      • 6.6.7. The negation pseudo-class
  • 7. Pseudo-elements
    • 7.1. The ::first-line pseudo-element
      • 7.1.1. First formatted line definition in CSS
    • 7.2. The ::first-letter pseudo-element
      • 7.2.1. Application in CSS
    • 7.3. Blank
    • 7.4. The ::before and ::after pseudo-elements
  • 8. Combinators
    • 8.1. Descendant combinator
    • 8.2. Child combinators
    • 8.3. Sibling combinators
      • 8.3.1. Adjacent sibling combinator
      • 8.3.2. General sibling combinator
  • 9. Calculating a selector's specificity
  • 10. The grammar of Selectors
    • 10.1. Grammar
    • 10.2. Lexical scanner
  • 11. Profiles
  • 12. Conformance and requirements
  • 13. Tests
  • 14. Acknowledgements
  • 15. References
    • 15.1. Normative References
    • 15.2. Informative References

1. Introduction

Selectors Level 1 and Selectors Level 2 are defined as the subsets of selector functionality defined in the CSS1 and CSS2.1 specifications, respectively.

1.1. Dependencies

Some features of this specification are specific to CSS, or have particular limitations or rules specific to CSS. In this specification, these have been described in terms of CSS2.1. [CSS21]

1.2. Terminology

All of the text of this specification is normative except examples, notes, and sections explicitly marked as non-normative.

Additional terminology is defined in the Definitions section of [CSS21]. Examples of document source code and fragments are given in XML [[XML10] or HTML [[HTML40]] syntax.

1.3. Changes from CSS2

This section is non-normative.

The main differences between the selectors in CSS2 and those in Selectors are:

  • the list of basic definitions (selector, group of selectors, simple selector, etc.) has been changed; in particular, what was referred to in CSS2 as a simple selector is now called a sequence of simple selectors, and the term "simple selector" is now used for the components of this sequence
  • an optional namespace component is now allowed in element type selectors, the universal selector and attribute selectors
  • a new combinator has been introduced
  • new simple selectors including substring matching attribute selectors, and new pseudo-classes
  • new pseudo-elements, and introduction of the "::" convention for pseudo-elements
  • the grammar has been rewritten
  • profiles to be added to specifications integrating Selectors and defining the set of selectors which is actually supported by each specification
  • Selectors are now a CSS3 Module and an independent specification; other specifications can now refer to this document independently of CSS
  • the specification now has its own test suite

2. Selectors

This section is non-normative, as it merely summarizes the following sections.

A Selector represents a structure. This structure can be used as a condition (e.g. in a CSS rule) that determines which elements a selector matches in the document tree, or as a flat description of the HTML or XML fragment corresponding to that structure.

Selectors may range from simple element names to rich contextual representations.

The following table summarizes the Selector syntax:

Pattern | Meaning | Described in section | First defined in CSS level
* | any element | Universal selector | 2
E | an element of type E | Type selector | 1
E[foo] | an E element with a "foo" attribute | Attribute selectors | 2
E[foo="bar"] | an E element whose "foo" attribute value is exactly equal to "bar" | Attribute selectors | 2
E[foo~="bar"] | an E element whose "foo" attribute value is a list of whitespace-separated values, one of which is exactly equal to "bar" | Attribute selectors | 2
E[foo^="bar"] | an E element whose "foo" attribute value begins exactly with the string "bar" | Attribute selectors | 3
E[foo$="bar"] | an E element whose "foo" attribute value ends exactly with the string "bar" | Attribute selectors | 3
E[foo*="bar"] | an E element whose "foo" attribute value contains the substring "bar" | Attribute selectors | 3
E[foo|="en"] | an E element whose "foo" attribute has a hyphen-separated list of values beginning (from the left) with "en" | Attribute selectors | 2
E:root | an E element, root of the document | Structural pseudo-classes | 3
E:nth-child(n) | an E element, the n-th child of its parent | Structural pseudo-classes | 3
E:nth-last-child(n) | an E element, the n-th child of its parent, counting from the last one | Structural pseudo-classes | 3
E:nth-of-type(n) | an E element, the n-th sibling of its type | Structural pseudo-classes | 3
E:nth-last-of-type(n) | an E element, the n-th sibling of its type, counting from the last one | Structural pseudo-classes | 3
E:first-child | an E element, first child of its parent | Structural pseudo-classes | 2
E:last-child | an E element, last child of its parent | Structural pseudo-classes | 3
E:first-of-type | an E element, first sibling of its type | Structural pseudo-classes | 3
E:last-of-type | an E element, last sibling of its type | Structural pseudo-classes | 3
E:only-child | an E element, only child of its parent | Structural pseudo-classes | 3
E:only-of-type | an E element, only sibling of its type | Structural pseudo-classes | 3
E:empty | an E element that has no children (including text nodes) | Structural pseudo-classes | 3
E:link E:visited | an E element being the source anchor of a hyperlink of which the target is not yet visited (:link) or already visited (:visited) | The link pseudo-classes | 1
E:active E:hover E:focus | an E element during certain user actions | The user action pseudo-classes | 1 and 2
E:target | an E element being the target of the referring URI | The target pseudo-class | 3
E:lang(fr) | an element of type E in language "fr" (the document language specifies how language is determined) | The :lang() pseudo-class | 2
E:enabled E:disabled | a user interface element E which is enabled or disabled | The UI element states pseudo-classes | 3
E:checked | a user interface element E which is checked (for instance a radio-button or checkbox) | The UI element states pseudo-classes | 3
E::first-line | the first formatted line of an E element | The ::first-line pseudo-element | 1
E::first-letter | the first formatted letter of an E element | The ::first-letter pseudo-element | 1
E::before | generated content before an E element | The ::before pseudo-element | 2
E::after | generated content after an E element | The ::after pseudo-element | 2
E.warning | an E element whose class is "warning" (the document language specifies how class is determined). | Class selectors | 1
E#myid | an E element with ID equal to "myid". | ID selectors | 1
E:not(s) | an E element that does not match simple selector s | Negation pseudo-class | 3
E F | an F element descendant of an E element | Descendant combinator | 1
E > F | an F element child of an E element | Child combinator | 2
E + F | an F element immediately preceded by an E element | Adjacent sibling combinator | 2
E ~ F | an F element preceded by an E element | General sibling combinator | 3

The meaning of each selector is derived from the table above by prepending "matches" to the contents of each cell in the "Meaning" column.

3. Case sensitivity

All Selectors syntax is case-insensitive within the ASCII range (i.e. [a-z] and [A-Z] are equivalent), except for parts that are not under the control of Selectors. The case sensitivity of document language element names, attribute names, and attribute values in selectors depends on the document language. For example, in HTML, element names are case-insensitive, but in XML, they are case-sensitive. Case sensitivity of namespace prefixes is defined in [CSS3NAMESPACE].

4. Selector syntax

A selector is a chain of one or more sequences of simple selectors separated by combinators. One pseudo-element may be appended to the last sequence of simple selectors in a selector.

A sequence of simple selectors is a chain of simple selectors that are not separated by a combinator. It always begins with a type selector or a universal selector. No other type selector or universal selector is allowed in the sequence.

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, or pseudo-class.

Combinators are: whitespace, "greater-than sign" (U+003E, >), "plus sign" (U+002B, +) and "tilde" (U+007E, ~). White space may appear between a combinator and the simple selectors around it. Only the characters "space" (U+0020), "tab" (U+0009), "line feed" (U+000A), "carriage return" (U+000D), and "form feed" (U+000C) can occur in whitespace. Other space-like characters, such as "em-space" (U+2003) and "ideographic space" (U+3000), are never part of whitespace.

The elements of a document tree that are represented by a selector are the subjects of the selector. A selector consisting of a single sequence of simple selectors represents any element satisfying its requirements. Prepending another sequence of simple selectors and a combinator to a sequence imposes additional matching constraints, so the subjects of a selector are always a subset of the elements represented by the last sequence of simple selectors.

An empty selector, containing no sequence of simple selectors and no pseudo-element, is an invalid selector.

Characters in Selectors can be escaped with a backslash according to the same escaping rules as CSS. [CSS21].

Certain selectors support namespace prefixes. The mechanism by which namespace prefixes are declared should be specified by the language that uses Selectors. If the language does not specify a namespace prefix declaration mechanism, then no prefixes are declared. In CSS, namespace prefixes are declared with the @namespace rule. [CSS3NAMESPACE]

5. Groups of selectors

A comma-separated list of selectors represents the union of all elements selected by each of the individual selectors in the list. (A comma is U+002C.) For example, in CSS when several selectors share the same declarations, they may be grouped into a comma-separated list. White space may appear before and/or after the comma.

CSS example:

In this example, we condense three rules with identical declarations into one. Thus,

h1 { font-family: sans-serif }
h2 { font-family: sans-serif }
h3 { font-family: sans-serif }

is equivalent to:

h1, h2, h3 { font-family: sans-serif }

Warning: the equivalence is true in this example because all the selectors are valid selectors. If just one of these selectors were invalid, the entire group of selectors would be invalid. This would invalidate the rule for all three heading elements, whereas in the former case only one of the three individual heading rules would be invalidated.

Invalid CSS example:

h1 { font-family: sans-serif }
h2..foo { font-family: sans-serif }
h3 { font-family: sans-serif }

is not equivalent to:

h1, h2..foo, h3 { font-family: sans-serif }

because the above selector (h1, h2..foo, h3) is entirely invalid and the entire style rule is dropped. (When the selectors are not grouped, only the rule for h2..foo is dropped.)

6. Simple selectors

6.1. Type selector

A type selector is the name of a document language element type written using the syntax of CSS qualified names [CSS3NAMESPACE]. A type selector represents an instance of the element type in the document tree.

Example:

The following selector represents an h1 element in the document tree:

h1

6.1.1. Type selectors and namespaces

Type selectors allow an optional namespace component: a namespace prefix that has been previously declared may be prepended to the element name separated by the namespace separator "vertical bar" (U+007C, |). (See, e.g., [XML-NAMES] for the use of namespaces in XML.)

The namespace component may be left empty (no prefix before the namespace separator) to indicate that the selector is only to represent elements with no namespace.

An asterisk may be used for the namespace prefix, indicating that the selector represents elements in any namespace (including elements with no namespace).

Element type selectors that have no namespace component (no namespace separator) represent elements without regard to the element's namespace (equivalent to "*|") unless a default namespace has been declared for namespaced selectors (e.g. in CSS, in the style sheet). If a default namespace has been declared, such selectors will represent only elements in the default namespace.

A type selector containing a namespace prefix that has not been previously declared for namespaced selectors is an invalid selector.

In a namespace-aware client, the name part of element type selectors (the part after the namespace separator, if it is present) will only match against the local part of the element's qualified name.

In summary:

ns|E
elements with name E in namespace ns
*|E
elements with name E in any namespace, including those without a namespace
|E
elements with name E without a namespace
E
if no default namespace has been declared for selectors, this is equivalent to *|E. Otherwise it is equivalent to ns|E where ns is the default namespace.

CSS examples:

@namespace foo url(http://www.example.com);
 foo|h1 { color: blue }  /* first rule */
 foo|* { color: yellow } /* second rule */
 |h1 { color: red }      /* ...*/
 *|h1 { color: green }
 h1 { color: green }

The first rule (not counting the @namespace at-rule) will match only h1 elements in the "http://www.example.com" namespace.

The second rule will match all elements in the "http://www.example.com" namespace.

The third rule will match only h1 elements with no namespace.

The fourth rule will match h1 elements in any namespace (including those without any namespace).

The last rule is equivalent to the fourth rule because no default namespace has been defined.

6.2. Universal selector

The universal selector, written as a CSS qualified name [CSS3NAMESPACE] with an asterisk (* U+002A) as the local name, represents the qualified name of any element type. It represents any single element in the document tree in any namespace (including those without a namespace) if no default namespace has been specified for selectors. If a default namespace has been specified, see Universal selector and Namespaces below.

If a universal selector represented by * (i.e. without a namespace prefix) is not the only component of a sequence of simple selectors selectors or is immediately followed by a pseudo-element, then the * may be omitted and the universal selector's presence implied.

Examples:

  • *[hreflang|=en] and [hreflang|=en] are equivalent,
  • *.warning and .warning are equivalent,
  • *#myid and #myid are equivalent.

Note: it is recommended that the * not be omitted, because it decreases the potential confusion between, for example, div :first-child and div:first-child. Here, div *:first-child is more readable.

6.2.1. Universal selector and namespaces

The universal selector allows an optional namespace component. It is used as follows:

ns|*
all elements in namespace ns
*|*
all elements
|*
all elements without a namespace
*
if no default namespace has been specified, this is equivalent to *|*. Otherwise it is equivalent to ns|* where ns is the default namespace.

A universal selector containing a namespace prefix that has not been previously declared is an invalid selector.

6.3. Attribute selectors

Selectors allow the representation of an element's attributes. When a selector is used as an expression to match against an element, attribute selectors must be considered to match an element if that element has an attribute that matches the attribute represented by the attribute selector.

6.3.1. Attribute presence and value selectors

CSS2 introduced four attribute selectors:

[att]
Represents an element with the att attribute, whatever the value of the attribute.
[att=val]
Represents an element with the att attribute whose value is exactly "val".
[att~=val]
Represents an element with the att attribute whose value is a whitespace-separated list of words, one of which is exactly "val". If "val" contains whitespace, it will never represent anything (since the words are separated by spaces). Also if "val" is the empty string, it will never represent anything.
[att|=val]
Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D). This is primarily intended to allow language subcode matches (e.g., the hreflang attribute on the a element in HTML) as described in BCP 47 ([BCP47]) or its successor. For lang (or xml:lang) language subcode matching, please see the :lang pseudo-class.

Attribute values must be CSS identifiers or strings. [CSS21] The case-sensitivity of attribute names and values in selectors depends on the document language.

Examples:

The following attribute selector represents an h1 element that carries the title attribute, whatever its value:

h1[title]

In the following example, the selector represents a span element whose class attribute has exactly the value "example":

span[class="example"]

Multiple attribute selectors can be used to represent several attributes of an element, or several conditions on the same attribute. Here, the selector represents a span element whose hello attribute has exactly the value "Cleveland" and whose goodbye attribute has exactly the value "Columbus":

span[hello="Cleveland"][goodbye="Columbus"]

The following CSS rules illustrate the differences between "=" and "~=". The first selector would match, for example, an a element with the value "copyright copyleft copyeditor" on a rel attribute. The second selector would only match an a element with an href attribute having the exact value "http://www.w3.org/".

a[rel~="copyright"] { ... }
a[href="http://www.w3.org/"] { ... }

The following selector represents an a element whose hreflang attribute is exactly "fr".

a[hreflang=fr]

The following selector represents an a element for which the value of the hreflang attribute begins with "en", including "en", "en-US", and "en-scouse":

a[hreflang|="en"]

The following selectors represent a DIALOGUE element whenever it has one of two different values for an attribute character:

DIALOGUE[character=romeo]
DIALOGUE[character=juliet]

6.3.2. Substring matching attribute selectors

Three additional attribute selectors are provided for matching substrings in the value of an attribute:

[att^=val]
Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.
[att$=val]
Represents an element with the att attribute whose value ends with the suffix "val". If "val" is the empty string then the selector does not represent anything.
[att*=val]
Represents an element with the att attribute whose value contains at least one instance of the substring "val". If "val" is the empty string then the selector does not represent anything.

Attribute values must be CSS identifiers or strings. [CSS21] The case-sensitivity of attribute names in selectors depends on the document language.

Examples:

The following selector represents an HTML object, referencing an image:

object[type^="image/"]

The following selector represents an HTML anchor a with an href attribute whose value ends with ".html".

a[href$=".html"]

The following selector represents an HTML paragraph with a title attribute whose value contains the substring "hello"

p[title*="hello"]

6.3.3. Attribute selectors and namespaces

The attribute name in an attribute selector is given as a CSS qualified name: a namespace prefix that has been previously declared may be prepended to the attribute name separated by the namespace separator "vertical bar" (|). In keeping with the Namespaces in the XML recommendation, default namespaces do not apply to attributes, therefore attribute selectors without a namespace component apply only to attributes that have no namespace (equivalent to "|attr"; these attributes are said to be in the "per-element-type namespace partition"). An asterisk may be used for the namespace prefix indicating that the selector is to match all attribute names without regard to the attribute's namespace.

An attribute selector with an attribute name containing a namespace prefix that has not been previously declared is an invalid selector.

CSS examples:

@namespace foo "http://www.example.com";
[foo|att=val] { color: blue }
[*|att] { color: yellow }
[|att] { color: green }
[att] { color: green }

The first rule will match only elements with the attribute att in the "http://www.example.com" namespace with the value "val".

The second rule will match only elements with the attribute att regardless of the namespace of the attribute (including no namespace).

The last two rules are equivalent and will match only elements with the attribute att where the attribute is not in a namespace.

6.3.4. Default attribute values in DTDs

Attribute selectors represent attribute values in the document tree. How that document tree is constructed is outside the scope of Selectors. In some document formats default attribute values can be defined in a DTD or elsewhere, but these can only be selected by attribute selectors if they appear in the document tree. Selectors should be designed so that they work whether or not the default values are included in the document tree.

For example, a XML UA may, but is not required to read an "external subset" of the DTD but is required to look for default attribute values in the document's "internal subset." (See, e.g., [XML10] for definitions of these subsets.) Depending on the UA, a default attribute value defined in the external subset of the DTD might or might not appear in the document tree.

A UA that recognizes an XML namespace may, but is not required to use its knowledge of that namespace to treat default attribute values as if they were present in the document. (For example, an XHTML UA is not required to use its built-in knowledge of the XHTML DTD. See, e.g., [XML-NAMES] for details on namespaces in XML 1.0.)

Note: Typically, implementations choose to ignore external subsets. This corresponds to the behaviour of non-validating processors as defined by the XML specification.

Example:

Consider an element EXAMPLE with an attribute radix that has a default value of "decimal". The DTD fragment might be

<!ATTLIST EXAMPLE radix (decimal,octal) "decimal">

If the style sheet contains the rules

EXAMPLE[radix=decimal] { /*... default property settings ...*/ }
EXAMPLE[radix=octal]   { /*... other settings...*/ }

the first rule might not match elements whose radix attribute is set by default, i.e. not set explicitly. To catch all cases, the attribute selector for the default value must be dropped:

EXAMPLE                { /*... default property settings ...*/ }
EXAMPLE[radix=octal]   { /*... other settings...*/ }

Here, because the selector EXAMPLE[radix=octal] is more specific than the type selector alone, the style declarations in the second rule will override those in the first for elements that have a radix attribute value of "octal". Care has to be taken that all property declarations that are to apply only to the default case are overridden in the non-default cases' style rules.

6.4. Class selectors

Working with HTML, authors may use the "period" notation (also known as "full stop", U+002E, .) as an alternative to the ~= notation when representing the class attribute. Thus, for HTML, div.value and div[class~=value] have the same meaning. The attribute value must immediately follow the full stop (.).

UAs may apply selectors using the period (.) notation in XML documents if the UA has namespace-specific knowledge that allows it to determine which attribute is the "class" attribute for the respective namespace. One such example of namespace-specific knowledge is the prose in the specification for a particular namespace (e.g. SVG 1.0 [SVG11] describes the SVG class attribute and how a UA should interpret it, and similarly MathML 1.01 [MATHML] describes the MathML class attribute.)

CSS examples:

We can assign style information to all elements with class~="pastoral" as follows:

*.pastoral { color: green }  /* all elements with class~=pastoral */

or just

.pastoral { color: green }  /* all elements with class~=pastoral */

The following assigns style only to H1 elements with class~="pastoral":

H1.pastoral { color: green }  /* H1 elements with class~=pastoral */

Given these rules, the first H1 instance below would not have green text, while the second would:

<H1>Not green</H1>
<H1 class="pastoral">Very green</H1>

The following rule matches any P element whose class attribute has been assigned a list of whitespace-separated values that includes both pastoral and marine:

p.pastoral.marine { color: green }

This rule matches when class="pastoral blue aqua marine" but does not match for class="pastoral blue".

Note: Because CSS gives considerable power to the "class" attribute, authors could conceivably design their own "document language" based on elements with almost no associated presentation (such as DIV and SPAN in HTML) and assigning style information through the "class" attribute. Authors should avoid this practice since the structural elements of a document language often have recognized and accepted meanings and author-defined classes may not.

Note: If an element has multiple class attributes, their values must be concatenated with spaces between the values before searching for the class. As of this time the working group is not aware of any manner in which this situation can be reached, however, so this behavior is explicitly non-normative in this specification.

6.5. ID selectors

Document languages may contain attributes that are declared to be of type ID. What makes attributes of type ID special is that no two such attributes can have the same value in a conformant document, regardless of the type of the elements that carry them; whatever the document language, an ID typed attribute can be used to uniquely identify its element. In HTML all ID attributes are named "id"; XML applications may name ID attributes differently, but the same restriction applies.

An ID-typed attribute of a document language allows authors to assign an identifier to one element instance in the document tree. An ID selector contains a "number sign" (U+0023, #) immediately followed by the ID value, which must be an CSS identifiers. An ID selector represents an element instance that has an identifier that matches the identifier in the ID selector.

Selectors does not specify how a UA knows the ID-typed attribute of an element. The UA may, e.g., read a document's DTD, have the information hard-coded or ask the user.

Examples:

The following ID selector represents an h1 element whose ID-typed attribute has the value "chapter1":

h1#chapter1

The following ID selector represents any element whose ID-typed attribute has the value "chapter1":

#chapter1

The following selector represents any element whose ID-typed attribute has the value "z98y".

*#z98y

Note: In XML 1.0 [XML10], the information about which attribute contains an element's IDs is contained in a DTD or a schema. When parsing XML, UAs do not always read the DTD, and thus may not know what the ID of an element is (though a UA may have namespace-specific knowledge that allows it to determine which attribute is the ID attribute for that namespace). If a style sheet author knows or suspects that a UA may not know what the ID of an element is, he should use normal attribute selectors instead: [name=p371] instead of #p371.

If an element has multiple ID attributes, all of them must be treated as IDs for that element for the purposes of the ID selector. Such a situation could be reached using mixtures of xml:id, DOM3 Core, XML DTDs, and namespace-specific knowledge.

6.6. Pseudo-classes

The pseudo-class concept is introduced to permit selection based on information that lies outside of the document tree or that cannot be expressed using the other simple selectors.

A pseudo-class always consists of a "colon" (:) followed by the name of the pseudo-class and optionally by a value between parentheses.

Pseudo-classes are allowed in all sequences of simple selectors contained in a selector. Pseudo-classes are allowed anywhere in sequences of simple selectors, after the leading type selector or universal selector (possibly omitted). Pseudo-class names are case-insensitive. Some pseudo-classes are mutually exclusive, while others can be applied simultaneously to the same element. Pseudo-classes may be dynamic, in the sense that an element may acquire or lose a pseudo-class while a user interacts with the document.

6.6.1. Dynamic pseudo-classes

Dynamic pseudo-classes classify elements on characteristics other than their name, attributes, or content, in principle characteristics that cannot be deduced from the document tree.

Dynamic pseudo-classes do not appear in the document source or document tree.

6.6.1.1. The link pseudo-classes: :link and :visited

User agents commonly display unvisited links differently from previously visited ones. Selectors provides the pseudo-classes :link and :visited to distinguish them:

  • The :link pseudo-class applies to links that have not yet been visited.
  • The :visited pseudo-class applies once the link has been visited by the user.

After some amount of time, user agents may choose to return a visited link to the (unvisited) ‘:link’ state.

The two states are mutually exclusive.

Example:

The following selector represents links carrying class external and already visited:

a.external:visited

Note: It is possible for style sheet authors to abuse the :link and :visited pseudo-classes to determine which sites a user has visited without the user's consent.

UAs may therefore treat all links as unvisited links, or implement other measures to preserve the user's privacy while rendering visited and unvisited links differently.

6.6.1.2. The user action pseudo-classes :hover, :active, and :focus

Interactive user agents sometimes change the rendering in response to user actions. Selectors provides three pseudo-classes for the selection of an element the user is acting on.

  • The :hover pseudo-class applies while the user designates an element with a pointing device, but does not necessarily activate it. For example, a visual user agent could apply this pseudo-class when the cursor (mouse pointer) hovers over a box generated by the element. User agents not that do not support interactive media do not have to support this pseudo-class. Some conforming user agents that support interactive media may not be able to support this pseudo-class (e.g., a pen device that does not detect hovering).
  • The :active pseudo-class applies while an element is being activated by the user. For example, between the times the user presses the mouse button and releases it. On systems with more than one mouse button, :active applies only to the primary or primary activation button (typically the "left" mouse button), and any aliases thereof.
  • The :focus pseudo-class applies while an element has the focus (accepts keyboard or mouse events, or other forms of input).

There may be document language or implementation specific limits on which elements can become :active or acquire :focus.

These pseudo-classes are not mutually exclusive. An element may match several pseudo-classes at the same time.

Selectors doesn't define if the parent of an element that is ‘:active’ or ‘:hover’ is also in that state.

Note: If the ‘:hover’ state applies to an element because its child is designated by a pointing device, then it's possible for ‘:hover’ to apply to an element that is not underneath the pointing device.

Examples:

a:link    /* unvisited links */
a:visited /* visited links */
a:hover   /* user hovers */
a:active  /* active links */

An example of combining dynamic pseudo-classes:

a:focus
a:focus:hover

The last selector matches a elements that are in the pseudo-class :focus and in the pseudo-class :hover.

Note: An element can be both ‘:visited’ and ‘:active’ (or ‘:link’ and ‘:active’).

6.6.2. The target pseudo-class :target

Some URIs refer to a location within a resource. This kind of URI ends with a "number sign" (#) followed by an anchor identifier (called the fragment identifier).

URIs with fragment identifiers link to a certain element within the document, known as the target element. For instance, here is a URI pointing to an anchor named section_2 in an HTML document:

http://example.com/html/top.html#section_2

A target element can be represented by the :target pseudo-class. If the document's URI has no fragment identifier, then the document has no target element.

Example:

p.note:target

This selector represents a p element of class note that is the target element of the referring URI.

CSS example:

Here, the :target pseudo-class is used to make the target element red and place an image before it, if there is one:

*:target { color : red }
*:target::before { content : url(target.png) }

6.6.3. The language pseudo-class :lang

If the document language specifies how the human language of an element is determined, it is possible to write selectors that represent an element based on its language. For example, in HTML [HTML401], the language is determined by a combination of the lang attribute and possibly information from the meta elements or the protocol (such as HTTP headers). XML uses an attribute called xml:lang, and there may be other document language-specific methods for determining the language.

The pseudo-class :lang(C) represents an element that is in language C. Whether an element is represented by a :lang() selector is based solely on the element's language value (normalized to BCP 47 syntax if necessary) being equal to the identifier C, or beginning with the identifier C immediately followed by "-" (U+002D). The matching of C against the element's language value is performed case-insensitively. The identifier C does not have to be a valid language name.

C must be a valid CSS identifier [CSS21] and must not be empty. (Otherwise, the selector is invalid.)

Note: It is recommended that documents and protocols indicate language using codes from BCP 47 [BCP47] or its successor, and by means of "xml:lang" attributes in the case of XML-based documents [XML10]. See "FAQ: Two-letter or three-letter language codes."

Examples:

The two following selectors represent an HTML document that is in Belgian French or German. The two next selectors represent q quotations in an arbitrary element in Belgian French or German.

html:lang(fr-be)
html:lang(de)
:lang(fr-be) > q
:lang(de) > q

The difference between :lang(C) and the ‘|=’ operator is that the ‘|=’ operator only performs a comparison against a given attribute on the element, while the :lang(C) pseudo-class uses the UAs knowledge of the document's semantics to perform the comparison.

In this HTML example, only the BODY matches [lang|=fr] (because it has a LANG attribute) but both the BODY and the P match :lang(fr) (because both are in French). The P does not match the [lang|=fr] because it does not have a LANG attribute.

<body lang=fr>
  <p>Je suis français.</p>
</body>

6.6.4. The UI element states pseudo-classes

6.6.4.1. The :enabled and :disabled pseudo-classes

The :enabled pseudo-class represents user interface elements that are in an enabled state; such elements have a corresponding disabled state.

Conversely, the :disabled pseudo-class represents user interface elements that are in a disabled state; such elements have a corresponding enabled state.

What constitutes an enabled state, a disabled state, and a user interface element is language-dependent. In a typical document most elements will be neither :enabled nor :disabled.

Note: CSS properties that might affect a user’s ability to interact with a given user interface element do not affect whether it matches :enabled or :disabled; e.g., the display and visibility properties have no effect on the enabled/disabled state of an element.

6.6.4.2. The :checked pseudo-class

Radio and checkbox elements can be toggled by the user. Some menu items are "checked" when the user selects them. When such elements are toggled "on" the :checked pseudo-class applies. While the :checked pseudo-class is dynamic in nature, and can altered by user action, since it can also be based on the presence of semantic attributes in the document, it applies to all media. For example, the :checked pseudo-class initially applies to such elements that have the HTML4 selected and checked attributes as described in Section 17.2.1 of HTML4, but of course the user can toggle "off" such elements in which case the :checked pseudo-class would no longer apply.

6.6.4.3. The :indeterminate pseudo-class

Note: Radio and checkbox elements can be toggled by the user, but are sometimes in an indeterminate state, neither checked nor unchecked. This can be due to an element attribute, or DOM manipulation.

A future version of this specification may introduce an :indeterminate pseudo-class that applies to such elements.

6.6.5. Structural pseudo-classes

Selectors introduces the concept of structural pseudo-classes to permit selection based on extra information that lies in the document tree but cannot be represented by other simple selectors or combinators.

Standalone text and other non-element nodes are not counted when calculating the position of an element in the list of children of its parent. When calculating the position of an element in the list of children of its parent, the index numbering starts at 1.

6.6.5.1. :root pseudo-class

The :root pseudo-class represents an element that is the root of the document. In HTML 4, this is always the HTML element.

6.6.5.2. :nth-child() pseudo-class

The :nth-child(an+b) pseudo-class notation represents an element that has a n+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element. For values of a and b greater than zero, this effectively divides the element's children into groups of a elements (the last group taking the remainder), and selecting the bth element of each group. For example, this allows the selectors to address every other row in a table, and could be used to alternate the color of paragraph text in a cycle of four. The a and b values must be integers (positive, negative, or zero). The index of the first child of an element is 1.

In addition to this, :nth-child() can take ‘odd’ and ‘even’ as arguments instead. ‘odd’ has the same signification as 2n+1, and ‘even’ has the same signification as 2n.

POWERED BY HeroNote

The argument to :nth-child() must match the grammar below, where INTEGER matches the token [0-9]+ and the rest of the tokenization is given by the Lexical scanner in section 10.2:

nth
  : S* [ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]? |
         ['-'|'+']? INTEGER | {O}{D}{D} | {E}{V}{E}{N} ] S*
  ;

Examples:

tr:nth-child(2n+1) /* represents every odd row of an HTML table */
tr:nth-child(odd)  /* same */
tr:nth-child(2n+0) /* represents every even row of an HTML table */
tr:nth-child(even) /* same */

/* Alternate paragraph colours in CSS */
p:nth-child(4n+1) { color: navy; }
p:nth-child(4n+2) { color: green; }
p:nth-child(4n+3) { color: maroon; }
p:nth-child(4n+4) { color: purple; }

When the value b is preceded by a negative sign, the "+" character in the expression must be removed (it is effectively replaced by the "-" character indicating the negative value of b).

Examples:

:nth-child(10n-1)  /* represents the 9th, 19th, 29th, etc, element */
:nth-child(10n+9)  /* Same */
:nth-child(10n+-1) /* Syntactically invalid, and would be ignored */

When a=0, the a n part need not be included (unless the b part is already omitted). When a n is not included and b is non-negative, the + sign before b (when allowed) may also be omitted. In this case the syntax simplifies to :nth-child(b).

Examples:

foo:nth-child(0n+5)   /* represents an element foo that is the 5th child
                         of its parent element */
foo:nth-child(5)      /* same */

When a=1, or a=-1, the number may be omitted from the rule.

Examples:

The following selectors are therefore equivalent:

bar:nth-child(1n+0)   /* represents all bar elements, specificity (0,1,1) */
bar:nth-child(n+0)    /* same */
bar:nth-child(n)      /* same */
bar                   /* same but lower specificity (0,0,1) */

If b=0, then every ath element is picked. In such a case, the +b (or -b) part may be omitted unless the a part is already omitted.

Examples:

tr:nth-child(2n+0) /* represents every even row of an HTML table */
tr:nth-child(2n) /* same */

Whitespace is permitted after the "(", before the ")", and on either side of the "+" or "-" that separates the a n and b parts when both are present.

Valid Examples with white space:

:nth-child( 3n + 1 )
:nth-child( +3n - 2 )
:nth-child( -n+ 6)
:nth-child( +6 )

Invalid Examples with white space:

:nth-child(3 n)
:nth-child(+ 2n)
:nth-child(+ 2)

If both a and b are equal to zero, the pseudo-class represents no element in the document tree.

The value a can be negative, but only the positive values of a n+b, for n≥0, may represent an element in the document tree.

Example:

html|tr:nth-child(-n+6)  /* represents the 6 first rows of XHTML tables */
6.6.5.3. :nth-last-child() pseudo-class

The :nth-last-child(an+b) pseudo-class notation represents an element that has a n+b-1 siblings after it in the document tree, for any positive integer or zero value of n, and has a parent element. See :nth-child() pseudo-class for the syntax of its argument. It also accepts the ‘even’ and ‘odd’ values as arguments.

Examples:

tr:nth-last-child(-n+2)    /* represents the two last rows of an HTML table */

foo:nth-last-child(odd)    /* represents all odd foo elements in their parent element,
                              counting from the last one */
6.6.5.4. :nth-of-type() pseudo-class

The :nth-of-type(an+b) pseudo-class notation represents an element that has a n+b-1 siblings with the same expanded element name before it in the document tree, for any zero or positive integer value of n, and has a parent element. See :nth-child() pseudo-class for the syntax of its argument. It also accepts the ‘even’ and ‘odd’ values.

CSS example:

This allows an author to alternate the position of floated images:

img:nth-of-type(2n+1) { float: right; }
img:nth-of-type(2n) { float: left; }
6.6.5.5. :nth-last-of-type() pseudo-class

The :nth-last-of-type(an+b) pseudo-class notation represents an element that has a n+b-1 siblings with the same expanded element name after it in the document tree, for any zero or positive integer value of n, and has a parent element. See :nth-child() pseudo-class for the syntax of its argument. It also accepts the ‘even’ and ‘odd’ values.

Example:

To represent all h2 children of an XHTML body except the first and last, one could use the following selector:

body > h2:nth-of-type(n+2):nth-last-of-type(n+2)

In this case, one could also use :not(), although the selector ends up being just as long:

body > h2:not(:first-of-type):not(:last-of-type)
6.6.5.6. :first-child pseudo-class

Same as :nth-child(1). The :first-child pseudo-class represents an element that is the first child of some other element.

Examples:

The following selector represents a p element that is the first child of a div element:

div > p:first-child

This selector can represent the p inside the div of the following fragment:

<p> The last P before the note.</p>
<div class="note">
   <p> The first P inside the note.</p>
</div>
but cannot represent the second p in the following fragment:
<p> The last P before the note.</p>
<div class="note">
   <h2> Note </h2>
   <p> The first P inside the note.</p>
</div>

The following two selectors are usually equivalent:

* > a:first-child /* a is first child of any element */
a:first-child /* Same (assuming a is not the root element) */
6.6.5.7. :last-child pseudo-class

Same as :nth-last-child(1). The :last-child pseudo-class represents an element that is the last child of some other element.

Example:

The following selector represents a list item li that is the last child of an ordered list ol.

ol > li:last-child
6.6.5.8. :first-of-type pseudo-class

Same as :nth-of-type(1). The :first-of-type pseudo-class represents an element that is the first sibling of its type in the list of children of its parent element.

Example:

The following selector represents a definition title dt inside a definition list dl, this dt being the first of its type in the list of children of its parent element.

dl dt:first-of-type

It is a valid description for the first two dt elements in the following example but not for the third one:

<dl>
 <dt>gigogne</dt>
 <dd>
  <dl>
   <dt>fusée</dt>
   <dd>multistage rocket</dd>
   <dt>table</dt>
   <dd>nest of tables</dd>
  </dl>
 </dd>
</dl>
6.6.5.9. :last-of-type pseudo-class

Same as :nth-last-of-type(1). The :last-of-type pseudo-class represents an element that is the last sibling of its type in the list of children of its parent element.

Example:

The following selector represents the last data cell td of a table row tr.

tr > td:last-of-type
6.6.5.10. :only-child pseudo-class

Represents an element that has a parent element and whose parent element has no other element children. Same as :first-child:last-child or :nth-child(1):nth-last-child(1), but with a lower specificity.

6.6.5.11. :only-of-type pseudo-class

Represents an element that has a parent element and whose parent element has no other element children with the same expanded element name. Same as :first-of-type:last-of-type or :nth-of-type(1):nth-last-of-type(1), but with a lower specificity.

6.6.5.12. :empty pseudo-class

The :empty pseudo-class represents an element that has no children at all. In terms of the document tree, only element nodes and content nodes (such as DOM [DOM-LEVEL-3-CORE] text nodes, CDATA nodes, and entity references) whose data has a non-zero length must be considered as affecting emptiness; comments, processing instructions, and other nodes must not affect whether an element is considered empty or not.

Examples:

p:empty is a valid representation of the following fragment:

<p></p>

foo:empty is not a valid representation for the following fragments:

<foo>bar</foo>
<foo><bar>bla</bar></foo>
<foo>this is not <bar>:empty</bar></foo>

6.6.6. Blank

This section intentionally left blank. (This section previously defined a :contains() pseudo-class.)

6.6.7. The negation pseudo-class

The negation pseudo-class, :not(X), is a functional notation taking a simple selector (excluding the negation pseudo-class itself) as an argument. It represents an element that is not represented by its argument.

Negations may not be nested; :not(:not(...)) is invalid. Note also that since pseudo-elements are not simple selectors, they are not a valid argument to :not().

Examples:

The following selector matches all button elements in an HTML document that are not disabled.

button:not([DISABLED])

The following selector represents all but FOO elements.

*:not(FOO)

The following group of selectors represents all HTML elements except links.

html|*:not(:link):not(:visited)

Default namespace declarations do not affect the argument of the negation pseudo-class unless the argument is a universal selector or a type selector.

Examples:

Assuming that the default namespace is bound to "http://example.com/", the following selector represents all elements that are not in that namespace:

*|*:not(*)

The following selector matches any element that is not being hovered, regardless of its namespace. In particular, it is not limited to only matching elements in the default namespace that are not being hovered, and elements not in the default namespace don't match the rule when they are being hovered.

*|*:not(:hover)

Note: the :not() pseudo allows useless selectors to be written. For instance :not(*|*), which represents no element at all, or foo:not(bar), which is equivalent to foo but with a higher specificity.

7. Pseudo-elements

Pseudo-elements create abstractions about the document tree beyond those specified by the document language. For instance, document languages do not offer mechanisms to access the first letter or first line of an element's content. Pseudo-elements allow authors to refer to this otherwise inaccessible information. Pseudo-elements may also provide authors a way to refer to content that does not exist in the source document (e.g., the ::before and ::after pseudo-elements give access to generated content).

A pseudo-element is made of two colons (::) followed by the name of the pseudo-element.

This :: notation is introduced by the current document in order to establish a discrimination between pseudo-classes and pseudo-elements. For compatibility with existing style sheets, user agents must also accept the previous one-colon notation for pseudo-elements introduced in CSS levels 1 and 2 (namely, :first-line, :first-letter, :before and :after). This compatibility is not allowed for the new pseudo-elements introduced in this specification.

Only one pseudo-element may appear per selector, and if present it must appear after the sequence of simple selectors that represents the subjects of the selector. Note: A future version of this specification may allow multiple pseudo-elements per selector.

7.1. The ::first-line pseudo-element

The ::first-line pseudo-element describes the contents of the first formatted line of an element.

CSS example:

p::first-line { text-transform: uppercase }

The above rule means "change the letters of the first line of every p element to uppercase".

The selector p::first-line does not match any real document element. It does match a pseudo-element that conforming user agents will insert at the beginning of every p element.

Note that the length of the first line depends on a number of factors, including the width of the page, the font size, etc. Thus, an ordinary HTML paragraph such as:

<P>This is a somewhat long HTML
paragraph that will be broken into several
lines. The first line will be identified
by a fictional tag sequence. The other lines
will be treated as ordinary lines in the
paragraph.</P>

the lines of which happen to be broken as follows:

THIS IS A SOMEWHAT LONG HTML PARAGRAPH THAT
will be broken into several lines. The first
line will be identified by a fictional tag
sequence. The other lines will be treated as
ordinary lines in the paragraph.

This paragraph might be "rewritten" by user agents to include the fictional tag sequence for ::first-line. This fictional tag sequence helps to show how properties are inherited.

<P><P::first-line> This is a somewhat long HTML
paragraph that </P::first-line> will be broken into several
lines. The first line will be identified
by a fictional tag sequence. The other lines
will be treated as ordinary lines in the
paragraph.</P>

If a pseudo-element breaks up a real element, the desired effect can often be described by a fictional tag sequence that closes and then re-opens the element. Thus, if we mark up the previous paragraph with a span element:

<P><SPAN class="test"> This is a somewhat long HTML
paragraph that will be broken into several
lines.</SPAN> The first line will be identified
by a fictional tag sequence. The other lines
will be treated as ordinary lines in the
paragraph.</P>

the user agent could simulate start and end tags for span when inserting the fictional tag sequence for ::first-line.

<P><P::first-line><SPAN class="test"> This is a
somewhat long HTML
paragraph that will </SPAN></P::first-line><SPAN class="test"> be
broken into several
lines.</SPAN> The first line will be identified
by a fictional tag sequence. The other lines
will be treated as ordinary lines in the
paragraph.</P>

7.1.1. First formatted line definition in CSS

In CSS, the ::first-line pseudo-element can only have an effect when attached to a block-like container such as a block box, inline-block, table-caption, or table-cell.

The first formatted line of an element may occur inside a block-level descendant in the same flow (i.e., a block-level descendant that is not out-of-flow due to floating or positioning). For example, the first line of the DIV in <DIV><P>This line...</P></DIV> is the first line of the P (assuming that both P and DIV are block-level).

The first line of a table-cell or inline-block cannot be the first formatted line of an ancestor element. Thus, in <DIV><P STYLE="display: inline-block">Hello<BR>Goodbye</P> etcetera</DIV> the first formatted line of the DIV is not the line "Hello".

Note: Note that the first line of the p in this fragment: <p><br>First... doesn't contain any letters (assuming the default style for br in HTML 4). The word "First" is not on the first formatted line.

A UA should act as if the fictional start tags of the ::first-line pseudo-elements were nested just inside the innermost enclosing block-level element. (Since CSS1 and CSS2 were silent on this case, authors should not rely on this behavior.) For example, the fictional tag sequence for

<DIV>
  <P>First paragraph</P>
  <P>Second paragraph</P>
</DIV>

is

<DIV>
  <P><DIV::first-line><P::first-line>First paragraph</P::first-line></DIV::first-line></P>
  <P><P::first-line>Second paragraph</P::first-line></P>
</DIV>

The ::first-line pseudo-element is similar to an inline-level element, but with certain restrictions. The following CSS properties apply to a ::first-line pseudo-element: font properties, color property, background properties, ‘word-spacing’, ‘letter-spacing’, ‘text-decoration’, ‘vertical-align’, ‘text-transform’, ‘line-height’. UAs may apply other properties as well.

During CSS inheritance, the portion of a child element that occurs on the first line only inherits properties applicable to the ::first-line pseudo-element from the ::first-line pseudo-element. For all other properties inheritence is from the non-pseudo-element parent of the first line pseudo element. (The portion of a child element that does not occur on the first line always inherits from the parent of that child.)

7.2. The ::first-letter pseudo-element

The ::first-letter pseudo-element represents the first letter of an element, if it is not preceded by any other content (such as images or inline tables) on its line. The ::first-letter pseudo-element may be used for "initial caps" and "drop caps", which are common typographical effects.

Punctuation (i.e, characters defined in Unicode in the "open" (Ps), "close" (Pe), "initial" (Pi). "final" (Pf) and "other" (Po) punctuation classes), that precedes or follows the first letter should be included. [UNICODE]

Quotes that precede the first letter should be included.

The ::first-letter also applies if the first letter is in fact a digit, e.g., the "6" in "67 million dollars is a lot of money."

Note: In some cases the ::first-letter pseudo-element should include more than just the first non-punctuation character on a line. For example, combining characters must be kept with their base character. Additionally, some languages may have specific rules about how to treat certain letter combinations. The UA definition of ::first-letter should include at least the default grapheme cluster as defined by UAX29 and may include more than that as appropriate. In Dutch, for example, if the letter combination "ij" appears at the beginning of an element, both letters should be considered within the ::first-letter pseudo-element. [UAX29]

If the letters that would form the ::first-letter are not in the same element, such as "‘T" in <p>'<em>T..., the UA may create a ::first-letter pseudo-element from one of the elements, both elements, or simply not create a pseudo-element.

Similarly, if the first letter(s) of the block are not at the start of the line (for example due to bidirectional reordering), then the UA need not create the pseudo-element(s).

Example:

The following CSS and HTML example illustrates how overlapping pseudo-elements may interact. The first letter of each P element will be green with a font size of ’24pt'. The rest of the first formatted line will be ‘blue’ while the rest of the paragraph will be ‘red’.

p { color: red; font-size: 12pt }
p::first-letter { color: green; font-size: 200% }
p::first-line { color: blue }

<P>Some text that ends up on two lines</P>

Assuming that a line break will occur before the word "ends", the fictional tag sequence for this fragment might be:

<P>
<P::first-line>
<P::first-letter>
S
</P::first-letter>ome text that
</P::first-line>
ends up on two lines
</P>

Note that the ::first-letter element is inside the ::first-line element. Properties set on ::first-line are inherited by ::first-letter, but are overridden if the same property is set on ::first-letter.

The first letter must occur on the first formatted line. For example, in this HTML fragment: <p><br>First... the first line doesn't contain any letters and ::first-letter doesn't match anything (assuming the default style for br in HTML 4). In particular, it does not match the "F" of "First."

7.2.1. Application in CSS

In CSS, the ::first-letter pseudo-element applies to block-like containers such as block, list-item, table-cell, table-caption, and inline-block elements. Note: A future version of this specification may allow this pseudo-element to apply to more display types.

The ::first-letter pseudo-element can be used with all such elements that contain text, or that have a descendant in the same flow that contains text. A UA should act as if the fictional start tag of the ::first-letter pseudo-element is just before the first text of the element, even if that first text is in a descendant.

Example:

The fictional tag sequence for this HTML fragment:

<div>
<p>The first text.

is:

<div>
<p><div::first-letter><p::first-letter>T</...></...>he first text.

In CSS the first letter of a table-cell or inline-block cannot be the first letter of an ancestor element. Thus, in <DIV><P STYLE="display: inline-block">Hello<BR>Goodbye</P> etcetera</DIV> the first letter of the DIV is not the letter "H". In fact, the DIV doesn't have a first letter.

If an element is a list item (‘display: list-item’), the ::first-letter applies to the first letter in the principal box after the marker. UAs may ignore ::first-letter on list items with ‘list-style-position: inside’. If an element has ::before or ::after content, the ::first-letter applies to the first letter of the element including that content.

Example:

After the rule p::before {content: "Note: "}, the selector p::first-letter matches the "N" of "Note".

In CSS a ::first-line pseudo-element is similar to an inline-level element if its ‘float’ property is ‘none’; otherwise, it is similar to a floated element. The following properties that apply to ::first-letter pseudo-elements: font properties, ‘text-decoration’, ‘text-transform’, ‘letter-spacing’, ‘word-spacing’ (when appropriate), ‘line-height’, ‘float’, ‘vertical-align’ (only if ‘float’ is ‘none’), margin properties, padding properties, border properties, color property, background properties. UAs may apply other properties as well. To allow UAs to render a typographically correct drop cap or initial cap, the UA may choose a line-height, width and height based on the shape of the letter, unlike for normal elements.

Example:

This CSS and HTML example shows a possible rendering of an initial cap. Note that the ‘line-height’ that is inherited by the ::first-letter pseudo-element is 1.1, but the UA in this example has computed the height of the first letter differently, so that it doesn't cause any unnecessary space between the first two lines. Also note that the fictional start tag of the first letter is inside the span, and thus the font weight of the first letter is normal, not bold as the span:

p { line-height: 1.1 }
p::first-letter { font-size: 3em; font-weight: normal }
span { font-weight: bold }
...
<p><span>Het hemelsche</span> gerecht heeft zich ten lange lesten<br>
Erbarremt over my en mijn benaeuwde vesten<br>
En arme burgery, en op mijn volcx gebed<br>
En dagelix geschrey de bange stad ontzet.

Image illustrating the ::first-letter pseudo-element

The following CSS will make a drop cap initial letter span about two lines:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
 <HEAD>
  <TITLE>Drop cap initial letter</TITLE>
  <STYLE type="text/css">
   P               { font-size: 12pt; line-height: 1.2 }
   P::first-letter { font-size: 200%; font-weight: bold; float: left }
   SPAN            { text-transform: uppercase }
  </STYLE>
 </HEAD>
 <BODY>
  <P><SPAN>The first</SPAN> few words of an article
    in The Economist.</P>
 </BODY>
</HTML>

This example might be formatted as follows:

Image illustrating the combined effect of the ::first-letter and ::first-line pseudo-elements

The fictional tag sequence is:

<P>
<SPAN>
<P::first-letter>
T
</P::first-letter>he first
</SPAN>
few words of an article in the Economist.
</P>

Note that the ::first-letter pseudo-element tags abut the content (i.e., the initial character), while the ::first-line pseudo-element start tag is inserted right after the start tag of the block element.

In order to achieve traditional drop caps formatting, user agents may approximate font sizes, for example to align baselines. Also, the glyph outline may be taken into account when formatting.

7.3. Blank

This section intentionally left blank. (This section previously defined a ::selection pseudo-element.)

7.4. The ::before and ::after pseudo-elements

The ::before and ::after pseudo-elements can be used to describe generated content before or after an element's content. They are explained in CSS 2.1 [CSS21].

When the ::first-letter and ::first-line pseudo-elements are applied to an element having content generated using ::before or ::after, they apply to the first letter or line of the element including the generated content.

8. Combinators

8.1. Descendant combinator

At times, authors may want selectors to describe an element that is the descendant of another element in the document tree (e.g., "an EM element that is contained within an H1 element"). Descendant combinators express such a relationship. A descendant combinator is whitespace that separates two sequences of simple selectors. A selector of the form "A B" represents an element B that is an arbitrary descendant of some ancestor element A.

Examples:

For example, consider the following selector:

h1 em

It represents an em element being the descendant of an h1 element. It is a correct and valid, but partial, description of the following fragment:

<h1>This <span class="myclass">headline
is <em>very</em> important</span></h1>

The following selector:

div * p

represents a p element that is a grandchild or later descendant of a div element. Note the whitespace on either side of the "*" is not part of the universal selector; the whitespace is a combinator indicating that the div must be the ancestor of some element, and that that element must be an ancestor of the p.

The following selector, which combines descendant combinators and attribute selectors, represents an element that (1) has the href attribute set and (2) is inside a p that is itself inside a div:

div p *[href]

8.2. Child combinators

A child combinator describes a childhood relationship between two elements. A child combinator is made of the "greater-than sign" (U+003E, >) character and separates two sequences of simple selectors.

Examples:

The following selector represents a p element that is child of body:

body > p

The following example combines descendant combinators and child combinators.

div ol>li p

It represents a p element that is a descendant of an li element; the li element must be the child of an ol element; the ol element must be a descendant of a div. Notice that the optional white space around the ">" combinator has been left out.

For information on selecting the first child of an element, please see the section on the :first-child pseudo-class above.

8.3. Sibling combinators

There are two different sibling combinators: the adjacent sibling combinator and the general sibling combinator. In both cases, non-element nodes (e.g. text between elements) are ignored when considering adjacency of elements.

8.3.1. Adjacent sibling combinator

The adjacent sibling combinator is made of the "plus sign" (U+002B, +) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence immediately precedes the element represented by the second one.

Examples:

The following selector represents a p element immediately following a math element:

math + p

The following selector is conceptually similar to the one in the previous example, except that it adds an attribute selector — it adds a constraint to the h1 element, that it must have class="opener":

h1.opener + h2

8.3.2. General sibling combinator

The general sibling combinator is made of the "tilde" (U+007E, ~) character that separates two sequences of simple selectors. The elements represented by the two sequences share the same parent in the document tree and the element represented by the first sequence precedes (not necessarily immediately) the element represented by the second one.

Example:

h1 ~ pre

represents a pre element following an h1. It is a correct and valid, but partial, description of:

<h1>Definition of the function a</h1>
<p>Function a(x) has to be applied to all figures in the table.</p>
<pre>function a(x) = 12x/13.5</pre>

9. Calculating a selector's specificity

A selector's specificity is calculated as follows:

  • count the number of ID selectors in the selector (= a)
  • count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= b)
  • count the number of type selectors and pseudo-elements in the selector (= c)
  • ignore the universal selector

Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class.

Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.

Examples:

*               /* a=0 b=0 c=0 -> specificity =   0 */
LI              /* a=0 b=0 c=1 -> specificity =   1 */
UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */

Note: Repeated occurrances of the same simple selector are allowed and do increase specificity.

Note: the specificity of the styles specified in an HTML style attribute is described in CSS 2.1. [CSS21].

10. The grammar of Selectors

10.1. Grammar

The grammar below defines the syntax of Selectors. It is globally LL(1) and can be locally LL(2) (but note that most UAs should not use it directly, since it doesn't express the parsing conventions). The format of the productions is optimized for human consumption and some shorthand notations beyond Yacc (see [YACC]) are used:

  • *: 0 or more
  • +: 1 or more
  • ?: 0 or 1
  • |: separates alternatives
  • [ ]: grouping

The productions are:

selectors_group
  : selector [ COMMA S* selector ]*
  ;

selector
  : simple_selector_sequence [ combinator simple_selector_sequence ]*
  ;

combinator
  /* combinators can be surrounded by whitespace */
  : PLUS S* | GREATER S* | TILDE S* | S+
  ;

simple_selector_sequence
  : [ type_selector | universal ]
    [ HASH | class | attrib | pseudo | negation ]*
  | [ HASH | class | attrib | pseudo | negation ]+
  ;

type_selector
  : [ namespace_prefix ]? element_name
  ;

namespace_prefix
  : [ IDENT | '*' ]? '|'
  ;

element_name
  : IDENT
  ;

universal
  : [ namespace_prefix ]? '*'
  ;

class
  : '.' IDENT
  ;

attrib
  : '[' S* [ namespace_prefix ]? IDENT S*
        [ [ PREFIXMATCH |
            SUFFIXMATCH |
            SUBSTRINGMATCH |
            '=' |
            INCLUDES |
            DASHMATCH ] S* [ IDENT | STRING ] S*
        ]? ']'
  ;

pseudo
  /* '::' starts a pseudo-element, ':' a pseudo-class */
  /* Exceptions: :first-line, :first-letter, :before and :after. */
  /* Note that pseudo-elements are restricted to one per selector and */
  /* occur only in the last simple_selector_sequence. */
  : ':' ':'? [ IDENT | functional_pseudo ]
  ;

functional_pseudo
  : FUNCTION S* expression ')'
  ;

expression
  /* In CSS3, the expressions are identifiers, strings, */
  /* or of the form "an+b" */
  : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+
  ;

negation
  : NOT S* negation_arg S* ')'
  ;

negation_arg
  : type_selector | universal | HASH | class | attrib | pseudo
  ;

10.2. Lexical scanner

The following is the tokenizer, written in Flex (see [FLEX]) notation. The tokenizer is case-insensitive.

The two occurrences of "\377" represent the highest character number that current versions of Flex can deal with (decimal 255). They should be read as "\4177777" (decimal 1114111), which is the highest possible code point in Unicode/ISO-10646. [UNICODE]

%option case-insensitive

ident     [-]?{nmstart}{nmchar}*
name      {nmchar}+
nmstart   [_a-z]|{nonascii}|{escape}
nonascii  [^\0-\177]
unicode   \\[0-9a-f]{1,6}(\r\n|[ \n\r\t\f])?
escape    {unicode}|\\[^\n\r\f0-9a-f]
nmchar    [_a-z0-9-]|{nonascii}|{escape}
num       [0-9]+|[0-9]*\.[0-9]+
string    {string1}|{string2}
string1   \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*\"
string2   \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*\'
invalid   {invalid1}|{invalid2}
invalid1  \"([^\n\r\f\\"]|\\{nl}|{nonascii}|{escape})*
invalid2  \'([^\n\r\f\\']|\\{nl}|{nonascii}|{escape})*
nl        \n|\r\n|\r|\f
w         [ \t\r\n\f]*

D         d|\\0{0,4}(44|64)(\r\n|[ \t\r\n\f])?
E         e|\\0{0,4}(45|65)(\r\n|[ \t\r\n\f])?
N         n|\\0{0,4}(4e|6e)(\r\n|[ \t\r\n\f])?|\\n
O         o|\\0{0,4}(4f|6f)(\r\n|[ \t\r\n\f])?|\\o
T         t|\\0{0,4}(54|74)(\r\n|[ \t\r\n\f])?|\\t
V         v|\\0{0,4}(58|78)(\r\n|[ \t\r\n\f])?|\\v

%%

[ \t\r\n\f]+     return S;

"~="             return INCLUDES;
"|="             return DASHMATCH;
"^="             return PREFIXMATCH;
"$="             return SUFFIXMATCH;
"*="             return SUBSTRINGMATCH;
{ident}          return IDENT;
{string}         return STRING;
{ident}"("       return FUNCTION;
{num}            return NUMBER;
"#"{name}        return HASH;
{w}"+"           return PLUS;
{w}">"           return GREATER;
{w}","           return COMMA;
{w}"~"           return TILDE;
":"{N}{O}{T}"("  return NOT;
@{ident}         return ATKEYWORD;
{invalid}        return INVALID;
{num}%           return PERCENTAGE;
{num}{ident}     return DIMENSION;
"<!--"           return CDO;
"-->"            return CDC;

\/\*[^*]*\*+([^/*][^*]*\*+)*\/                    /* ignore comments */

.                return *yytext;

11. Profiles

Each specification using Selectors must define the subset of Selectors it allows and excludes, and describe the local meaning of all the components of that subset.

Non normative examples:

Selectors profile
Specification | CSS level 1
Accepts | type selectors class selectors ID selectors :link, :visited and :active pseudo-classes descendant combinator ::first-line and ::first-letter pseudo-elements
Excludes | universal selector attribute selectors :hover and :focus pseudo-classes :target pseudo-class :lang() pseudo-class all UI element states pseudo-classes all structural pseudo-classes negation pseudo-class ::before and ::after pseudo-elements child combinators sibling combinators namespaces
Extra constraints | only one class selector allowed per sequence of simple selectors

Selectors profile
Specification | CSS level 2
Accepts | type selectors universal selector attribute presence and values selectors class selectors ID selectors :link, :visited, :active, :hover, :focus, :lang() and :first-child pseudo-classes descendant combinator child combinator adjacent sibling combinator ::first-line and ::first-letter pseudo-elements ::before and ::after pseudo-elements
Excludes | substring matching attribute selectors :target pseudo-classes all UI element states pseudo-classes all structural pseudo-classes other than :first-child negation pseudo-class general sibling combinators namespaces
Extra constraints | more than one class selector per sequence of simple selectors (CSS1 constraint) allowed

In CSS, selectors express pattern matching rules that determine which style rules apply to elements in the document tree.

The following selector (CSS level 2) will match all anchors a with attribute name set inside a section 1 header h1:

h1 a[name]

All CSS declarations attached to such a selector are applied to elements matching it.

Selectors profile
Specification | STTS 3
Accepts | type selectors universal selectors attribute selectors class selectors ID selectors all structural pseudo-classes all combinators namespaces
Excludes | non-accepted pseudo-classes pseudo-elements
Extra constraints | some selectors and combinators are not allowed in fragment descriptions on the right side of STTS declarations.

Selectors can be used in STTS 3 in two different manners:

  1. a selection mechanism equivalent to CSS selection mechanism: declarations attached to a given selector are applied to elements matching that selector,
  2. fragment descriptions that appear on the right side of declarations.

12. Conformance and requirements

This section defines conformance with the present specification only.

The inability of a user agent to implement part of this specification due to the limitations of a particular device (e.g., non interactive user agents will probably not implement dynamic pseudo-classes because they make no sense without interactivity) does not imply non-conformance.

All specifications reusing Selectors must contain a Profile listing the subset of Selectors it accepts or excludes, and describing the constraints it adds to the current specification.

Invalidity is caused by a parsing error, e.g. an unrecognized token or a token which is not allowed at the current parsing point.

User agents must observe the rules for handling parsing errors:

  • a simple selector containing an undeclared namespace prefix is invalid
  • a selector containing an invalid simple selector, an invalid combinator or an invalid token is invalid.
  • a group of selectors containing an invalid selector is invalid.

Specifications reusing Selectors must define how to handle parsing errors. (In the case of CSS, the entire rule in which the selector is used is dropped.)

13. Tests

This specification has a test suite allowing user agents to verify their basic conformance to the specification. This test suite does not pretend to be exhaustive and does not cover all possible combined cases of Selectors.

14. Acknowledgements

The CSS working group would like to thank everyone who has sent comments on this specification over the years.

In particular, the working group would like to extend special thanks to Donna McManus, Justin Baker, Joel Sklar, and Molly Ives Brower who performed the final editorial review of the last call draft. The working group would also like to thank Adam Kuehn, Boris Zbarsky, David Perrell, Elliotte Harold, Matthew Raymond, Ruud Steltenpool, Patrick Garies, Anton Prowse, and the W3C Internationalization Working Group for their last call comments and kind words.

15. References

15.1. Normative References

[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 8 September 2009. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2009/CR-CSS2-20090908
[CSS3NAMESPACE]
Anne van Kesteren; Elika J. Etemad. CSS Namespaces Module. 23 May 2008. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2008/CR-css3-namespace-20080523
[FLEX]
Flex: The Lexical Scanner Generator. Version 2.3.7, ISBN 1882114213
[UNICODE]
The Unicode Consortium. The Unicode Standard. 2003. Defined by: The Unicode Standard, Version 4.0 (Boston, MA, Addison-Wesley, ISBN 0-321-18578-1), as updated from time to time by the publication of new versions URL: http://www.unicode.org/unicode/standard/versions/enumeratedversions.html
[YACC]
S. C. Johnson. YACC - Yet another compiler compiler. Murray Hill. 1975. Technical Report.

15.2. Informative References

[BCP47]
H. Alvestrand. Tags for the Identification of Languages. January 2001. Internet Best Current Practice 47. BCP 47 is currently represented by RFC 3066. URL: ftp://ftp.rfc-editor.org/in-notes/bcp/bcp47.txt
[CSS1]
Håkon Wium Lie; Bert Bos. Cascading Style Sheets (CSS1) Level 1 Specification. 11 April 2008. W3C Recommendation. URL: http://www.w3.org/TR/2008/REC-CSS1-20080411
[DOM-LEVEL-3-CORE]
Gavin Nicol; et al. Document Object Model (DOM) Level 3 Core Specification. 7 April 2004. W3C Recommendation. URL: http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407
[HTML401]
David Raggett; Ian Jacobs; Arnaud Le Hors. HTML 4.01 Specification. 24 December 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-html401-19991224
[MATHML]
Patrick Ion; Robert Miner. Mathematical Markup Language (MathML) 1.01 Specification. 7 July 1999. W3C Recommendation. URL: http://www.w3.org/1999/07/REC-MathML-19990707
[STTS3]
Daniel Glazman. Simple Tree Transformation Sheets 3. Electricité de France. 11 November 1998. Submission to the W3C. URL: http://www.w3.org/TR/NOTE-STTS3
[SVG11]
Dean Jackson; 藤沢 淳; Jon Ferraiolo. Scalable Vector Graphics (SVG) 1.1 Specification. 14 January 2003. W3C Recommendation. URL: http://www.w3.org/TR/2003/REC-SVG11-20030114
[UAX29]
Mark Davis. Text Boundaries. 25 March 2005. Unicode Standard Annex #29. URL: http://www.unicode.org/unicode/reports/tr29/tr29-9.html
[XML-NAMES]
Tim Bray; et al. Namespaces in XML 1.0 (Third Edition). 6 August 2009. W3C Proposed Edited Recommendation. URL: http://www.w3.org/TR/2009/PER-xml-names-20090806
[XML10]
C. M. Sperberg-McQueen; et al. Extensible Markup Language (XML) 1.0 (Fifth Edition). 10 February 1998. W3C Proposed Edited Recommendation. Revised 5 February 2008 URL: http://www.w3.org/TR/2008/PER-xml-20080205


CSS3 Speech Module

W3C Working Draft 16 December 2004

This version:
http://www.w3.org/TR/2004/WD-css3-speech-20041216/
Latest version:
http://www.w3.org/TR/css3-speech
Previous version:
http://www.w3.org/TR/2004/WD-css3-speech-20040727/
Editors:
Dave Raggett (W3C/Canon)
Daniel Glazman (Disruptive Innovations)
Claudio Santambrogio (Opera Software)

Copyright © 2004 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark, document use.

Abstract

CSS (Cascading Style Sheets) is a language for describing the rendering of HTML and XML documents on screen, on paper, in speech, etc. CSS defines aural properties that give control over rendering XML to speech. This draft describes the text to speech properties proposed for CSS level 3. These are designed for match the model described in the Speech Synthesis Markup Language (SSML) Version 1.0 [SSML10]

The CSS3 Speech Module is a community effort and if you would like to help with implementation and driving the specification forward along the W3C Recommendation track, please contact the editors.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document is a draft of one of the "modules" for the upcoming CSS3 specification.

This document is a working draft of the CSS working group which is part of the style activity (see summary). It has been developed in cooperation with the Voice Browser working group (W3C Members only).

The CSS working group would like to receive feedback: comments on this draft may be sent to the editors, discussion takes place on the (archived) public mailing list www-style@w3.org (see instructions). W3C Members can also send comments directly to the CSS working group.

This document was produced under the 24 January 2002 CPP as amended by the W3C Patent Policy Transition Procedure. Patent disclosures relevant to CSS may be found on the Working Group's public patent disclosure page.

Candidate Recommendation Exit Criteria

For this specification to exit the CR stage, the following conditions must be met:

  1. There must be at least two interoperable implementations for every feature. For the purposes of this criterion, we define the following terms:

    feature

    A section or subsection of the specification.

    interoperable

    passing the respective test cases in the test suite, or, if the implementation is not a web browser, equivalent tests. Every relevant test in the test suite should have an equivalent test created if such a UA is to be used to claim interoperability. In addition if such a UA is to be used to claim interoperability, then there must one or more additional UAs which can also pass those equivalent tests in the same way for the purpose of interoperability. The equivalent tests must be made publicly available for the purposes of peer review.

    implementation

    a user agent which:

    1. implements the feature.
    2. is available (i.e. publicly downloadable or available through some other public point of sale mechanism). This is the "show me" requirement.
    3. is shipping (i.e. development, private or unofficial versions are insufficient).
    4. is not experimental (i.e. is intended for a wide audience and could be used on a daily basis).

  2. A minimum of six months of the CR period must have elapsed. This is to ensure that enough time is given for any remaining major errors to be caught.

  3. The CR period will be extended if implementations are slow to appear.

  4. Features that were not in CSS1 will be dropped (thus reducing the list of "all" features mentioned above) if two or more interoperable implementations of those features are not found by the end of the CR period.

  5. Features will also be dropped if sufficient and adequate tests (by judgment of the working group) have not been produced for those features by the end of the CR period.

Table of contents

  • Abstract
  • Status of this Document
    • Candidate Recommendation Exit Criteria
  • 1. Dependencies on other modules
  • 2. Introduction
  • 3. The aural "box" model
  • 4. Mixing properties
    • 'voice-volume'
    • 'voice-balance'
  • 5. Speaking properties
    • 'speak'
  • 6. Pause properties
    • 'pause-before'
    • 'pause-after'
    • 'pause'
    • Collapsing pauses
  • 7. Rest properties
    • 'rest-before'
    • 'rest-after'
    • 'rest'
  • 8. Cue properties
    • 'cue-before'
    • 'cue-after'
    • 'cue'
  • 9. Mark properties
    • 'mark-before'
    • 'mark-after'
    • 'mark'
  • 10. Voice characteristic properties
    • 'voice-family'
    • 'voice-rate'
    • 'voice-pitch'
    • 'voice-pitch-range'
    • 'voice-stress'
  • 11. Duration properties
    • 'voice-duration'
  • 12. Phonetics:
    • 'phonemes'
    • '@phonetic-alphabet'
    • 'content'
  • Appendix A - Changes from previous draft
  • Appendix B - Profiles
  • Appendix C - Acknowledgements
  • Appendix D - References
    • Normative references
    • Informative references
  • Appendix E - Property index

1. Dependencies on other modules

This CSS3 module depends on the following other CSS3 modules:

  • Cascade and Inheritance [CSS3CASCADE]
  • Tables [CSS3TABLES]
  • Syntax [CSS3SYN]
  • Values and Units [CSS3VAL]

It has non-normative (informative) references to the following other CSS3 modules:

  • The box model [CSS3BOX]
  • Generated and Replaced Content [CSS3GENCON]
  • Selectors [SELECT]

2. Introduction

The speech rendering of a document, already commonly used by the blind and print-impaired communities, combines speech synthesis and "auditory icons". Often such aural presentation occurs by converting the document to plain text and feeding this to a screen reader - software or hardware that simply reads all the characters on the screen. This results in less effective presentation than would be the case if the document structure were retained. Style sheet properties for text to speech may be used together with visual properties (mixed media) or as an aural alternative to visual presentation.

Besides the obvious accessibility advantages, there are other large markets for listening to information, including in-car use, industrial and medical documentation systems (intranets), home entertainment, and to help users learning to read or who have difficulty reading.

When using voice properties, the canvas consists of a two channel stereo space and a temporal space (you can specify audio cues before and after synthetic speech). The CSS properties also allow authors to vary the characteristics of synthetic speech (voice type, frequency, inflection, etc.).

Examples:

h1, h2, h3, h4, h5, h6 {
    voice-family: paul;
    voice-stress: moderate;
    cue-before: url(ping.au)
}
p.heidi { voice-balance: left; voice-family: female }
p.peter { voice-balance: right; voice-family: male }
p.goat  { voice-volume: soft }

This will direct the speech synthesizer to speak headers in a voice (a kind of "audio font") called "paul". Before speaking the headers, a sound sample will be played from the given URL. Paragraphs with class "heidi" will appear to come from the left (if the sound system is capable of stereo), and paragraphs of class "peter" from the right. Paragraphs with class "goat" will be played softly.

3. The aural "box" model

The formatting model of CSS for aural media is based on a sequence of sounds and silences that appear in a nested model which is related to the visual box model; however the aural canvas is one-dimensional, monolinear. For compatibility with the visual box model, we will call it the aural "box" model.

The element is surrounded by, in this order, 'rest', 'cue' and 'pause' properties - they can be thought of as aural equivalents to 'padding', 'border' and 'margin' respectively.

It can be represented in the following way (including the equivalent properties from the visual box model for clarification of relationships):

A graph depicting the aural 'box' model.

where element is the selected element to which the properties from the Speech Module apply.

4. Mixing properties: 'voice-volume' and 'voice-balance'

Name: | voice-volume
Value: | <number> | <percentage> | silent | x-soft | soft | medium | loud | x-loud | inherit
Initial: | medium
Applies to: | all elements
Inherited: | yes
Percentages: | refer to inherited value
Media: | speech

The 'voice-volume' refers to the amplitude of the waveform output by the speech synthesiser. This may be mixed with other audio sources, influencing the perceived loudness of synthetic speech relative to these sources. Note that voice-volume does not apply to audio cues for which there is a separate means to set the relative loudness.

Values have the following meanings:

<number>
An integer or floating point number in the range '0' to '100'. '0' represents silence (the minimum level), and 100 corresponds to the maximum level. The volume scale is linear amplitude.
<percentage>
Percentage values are calculated relative to the inherited value, and are then clipped to the range '0' to '100'.
silent, x-soft, soft, medium, loud, and x-loud
A sequence of monotonically non-decreasing volume levels. The value of 'silent' is mapped to '0' and 'x-loud' is mapped to '100'. The mapping of other values to numerical volume levels is implementation dependent and may vary from one speech synthesizer to the next.

User agents should allow the level corresponding to '100' to be set by the listener. No one setting is universally applicable; suitable values depend on the equipment in use (speakers, headphones), and the environment (in car, home theater, library) and personal preferences.

Name: | voice-balance
Value: | <number> | left | center | right | leftwards | rightwards | inherit
Initial: | center
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | speech

The 'voice-balance' property refers to the balance between left and right channels, and presumes a two channel (stereo) model that is widely supported on consumer audio equipment.

Values have the following meanings:

<number>
An integer or floating point number between '-100' and '100'. For '-100' only the left channel is audible. Simarly for '100' or '+100' only the right channel is audible. For '0' both channels have the same level, so that the speech appears to be coming from the center.
left
Same as '-100'.
center
Same as '0'.
right
Same as '100' or '+100'.
leftwards
Moves the sound to the left, relative to the inherited voice balance. More precisely, subtract 20 from the inherited value and clip the resulting value to the range '-100' and '100'.
rightwards
Moves the sound to the right, relative to the inherited voice balance. More precisely, add 20 to the inherited value and clip the resulting value to the range '-100' and '100'.

Many speech synthesizers only support a single channel. The voice-balance property can then be treated as part of a post synthesis mixing step. This is where speech is mixed with other audio sources. Note that unlike voice-volume, voice-balance does apply to cues.

5. Speaking properties: 'speak'

Name: | speak
Value: | none | normal | spell-out | digits | literal-punctuation | no-punctuation | inherit
Initial: | normal
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | speech

This property specifies whether text will be rendered aurally and if so, in what manner. The possible values are:

none
Suppresses aural rendering so that the element requires no time to render. Note, however, that descendants may override this value and will be spoken. (To be sure to suppress rendering of an element and its descendants, use the 'display' property [CSS3BOX]).
normal
Uses language-dependent pronunciation rules for rendering an element and its children. Punctuation is not to be spoken, but instead rendered naturally as various pauses.
spell-out
Spells the text one letter at a time (useful for acronyms and abbreviations). In languages where accented characters are rare, it is permitted to drop accents in favor of alternative unaccented spellings. As as example, in English, the word "rôle" can also be written as "role". A conforming implementation would thus be able to spell-out "rôle" as "R O L E".
digits
Speak numbers one digit at a time, for instance, "twelve" would be spoken as "one two", and "31" as "three one".
literal-punctuation
Similar to 'normal' value, but punctuation such as semicolons, braces, and so on are to be spoken literally.
no-punctuation
Similar to 'normal' value but punctuation is not to be spoken nor rendered as various pauses.

Note the difference between an element whose 'voice-volume' property has a value of 'silent' and an element whose 'speak' property has the value 'none'. The former takes up the same time as if it had been spoken, including any pause before and after the element, but no sound is generated. The latter requires no time and is not rendered (though its descendants may be).

Speech synthesizers are knowledgeable about what is and what is not a number. The speak property gives authors the means to control how the synthesizer renders the numbers it discovers in the source text, and may be implemented as a preprocessing step before passing the text to the speech synthesizer.

6. Pause properties: 'pause-before', 'pause-after' and 'pause', collapsing pauses

Name: | pause-before
Value: | <time> | none | x-weak | weak | medium | strong | x-strong | inherit
Initial: | implementation dependent
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | speech

Name: | pause-after
Value: | <time> | none | x-weak | weak | medium | strong | x-strong | inherit
Initial: | implementation dependent
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | speech

These properties specify a pause or prosodic boundary to be observed before (or after) an element or, if any 'cue-before' or 'cue-after' is specified, before (or after) these. Values have the following meanings:

<time>
Expresses the pause in absolute time units (seconds and milliseconds, e.g. "3s", "250ms"). Only positive values are allowed.
none, x-weak, weak, medium, strong, and x-strong
These values may be used to indicate the prosodic strength of the break in speech output. The synthesis processor may insert a pause as part of its implementation of the prosodic break. The value "none" indicates that no prosodic break boundary should be output, and can be used to inhibit a prosodic break which the processor would otherwise produce. The other values indicate monotonically non-decreasing (conceptually increasing) break strength between elements. The stronger boundaries are typically accompanied by pauses. "x-weak" and "x-strong" are mnemonics for "extra weak" and "extra strong", respectively. The breaks between paragraphs are typically much stronger than the breaks between words within a sentence.
Name: | pause
Value: | [ <'pause-before'> || <'pause-after'> ] | inherit
Initial: | implementation dependent
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | speech

The 'pause' property is a shorthand for setting 'pause-before' and 'pause-after'. If two values are given, the first value is 'pause-before' and the second is 'pause-after'. If only one value is given, it applies to both properties.

Examples:

h1 { pause: 20ms } /* pause-before: 20ms; pause-after: 20ms */
h2 { pause: 30ms 40ms } /* pause-before: 30ms; pause-after: 40ms */
h3 { pause-after: 10ms } /* pause-before: unspecified; pause-after: 10ms */

Collapsing pauses

The pause defines the minimum distance of the aural "box" to the aural "boxes" before and after it. Adjacent pauses should be merged by selecting the strongest named break or the longest absolute time interval. Thus "strong" is selected when comparing "strong" and "weak", while "1s" is selected when comparing "1s" and "250ms". We say that such pauses collapse. A combination of a named break and time duration is treated additively.

The following pauses collapse:

  1. The pause-after of an aural "box" and the pause-after of its last child, provided the former has no rest-after and no cue-after.
  2. The pause-before of an aural "box" and the pause-before of its first child, provided the former has no rest-before and no cue-before.
  3. The pause-after of an aural "box" and the pause-before of its next sibling.
  4. The pause-before and pause-after of an aural "box", if the the "box" has a voice-duration of "0ms", no rest-before or rest-after, no cue-before or cue-after and no content.

The pause-after of an element is always adjoining to the pause-before of its next sibling.

The pause-before an element is adjoining to its first child's pause-before, if the element has no cue-before nor rest-before.

The pause-after of an element is adjoining to its last child's pause-after, if the element has no rest-after or cue-after.

An element's own pauses are adjoining if the 'voice-duration' property is zero, and it has no rest, and it does not contain any content, and all of its children's pauses (if any) are adjoining.

Editor's note: 'pause' has been re-defined, and has been moved from between the element's contents and any 'cue' to outside the 'cue' - this is not backwards compatible with the informative CSS2.1 Aural appendix.

7. Rest properties: rest-before', 'rest-after' and 'rest'

Name: | rest-before
Value: | <time> | none | x-weak | weak | medium | strong | x-strong | inherit
Initial: | implementation dependent
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | speech

Name: | rest-after
Value: | <time> | none | x-weak | weak | medium | strong | x-strong | inherit
Initial: | implementation dependent
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | speech

These properties specify a rest or prosodic boundary to be observed before (or after) speaking an element's content. Values have the following meanings:

<time>
Expresses the rest in absolute time units (seconds and milliseconds, e.g. "3s", "250ms"). Only positive values are allowed.
none, x-weak, weak, medium, strong, and x-strong
These values may be used to indicate the prosodic strength of the break in speech output. The synthesis processor may insert a rest as part of its implementation of the prosodic break. The value "none" indicates that no prosodic break boundary should be output, and can be used to inhibit a prosodic break which the processor would otherwise produce. The other values indicate monotonically non-decreasing (conceptually increasing) break strength between words. The stronger boundaries are typically accompanied by rests. "x-weak" and "x-strong" are mnemonics for "extra weak" and "extra strong", respectively.

As opposed to pause properties, the rest is inserted between the element's content and any 'cue-before' or 'cue-after' content. Adjacent rests are treated additively.

Name: | rest
Value: | [ <'rest-before'> || <rest-after'> ] | inherit
Initial: | implementation dependent
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | speech

The 'rest' property is a shorthand for setting 'rest-before' and 'rest-after'. If two values are given, the first value is 'rest-before' and the second is 'rest-after'. If only one value is given, it applies to both properties.

8. Cue properties: 'cue-before', 'cue-after' and 'cue'

Name: | cue-before
Value: | <uri> [<number> | <percentage> | silent | x-soft | soft | medium | loud | x-loud] | none | inherit
Initial: | none
Applies to: | all elements
Inherited: | no
Percentages: | apply to inherited value for voice-volume
Media: | speech

Name: | cue-after
Value: | <uri> [<number> | <percentage> | silent | x-soft | soft | medium | loud | x-loud] | none | inherit
Initial: | none
Applies to: | all elements
Inherited: | no
Percentages: | apply to inherited value for voice-volume
Media: | speech

Auditory icons are another way to distinguish semantic elements. Sounds may be played before and/or after the element to delimit it. Values have the following meanings:

<uri>
The URI must designate an auditory icon resource. If the URI resolves to something other than an audio file, such as an image, the resource should be ignored and the property treated as if it had the value 'none'.
none
No auditory icon is specified.
<number>
An integer or floating point number in the range '0' to '100'. '0' represents silence (the minimum level), and 100 corresponds to the maximum level. The volume scale is linear amplitude.
<percentage>
Percentage values are calculated relative to the inherited value of the 'voice-volume' property, and are then clipped to the range '0' to '100'. By basing the percentage upon the inherited value for voice-volume, it is easy to adjust the relative loudness of cues compared to synthetic speech for whatever volume setting has been provided for that speech.
silent, x-soft, soft, medium, loud, and x-loud
A sequence of monotonically non-decreasing volume levels. The value of 'silent' is mapped to '0' and 'x-loud' is mapped to '100'. The mapping of other values to numerical volume levels is implementation dependent, but the intention is to match the corresponding levels for voice-volume.

Examples:

a { cue-before: url(bell.aiff); cue-after: url(dong.wav) }

h1 { cue-before: url(pop.au) 80; cue-after: url(pop.au) 50% }

div.caution { cue-before: url(caution.wav) loud }

Name: | cue
Value: | [ <'cue-before'> || <'cue-after'> ] | inherit
Initial: | not defined for shorthand properties
Applies to: | all elements
Inherited: | no
Percentages: | apply to inherited value for voice-volume
Media: | speech

The 'cue' property is a shorthand for setting 'cue-before' and 'cue-after'. If two values are given the first value is 'cue-before' and the second is 'cue-after'. If only one value is given, it applies to both properties.

The following two rules are equivalent:

h1 {cue-before: url(pop.au); cue-after: url(pop.au) }

h1 {cue: url(pop.au) }

If a user agent cannot render an auditory icon (e.g., the user's environment does not permit it), we recommend that it produce an alternative cue (e.g., popping up a warning, emitting a warning sound, etc.)

Please see the sections on the ::before and ::after pseudo-elements [SELECT] for information on other content generation techniques.

9. Mark properties: 'mark-before', 'mark-after' and 'mark'

POWERED BY HeroNote
Name: | mark-before
Value: | <string>
Initial: | none
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | speech

Name: | mark-after
Value: | <string>
Initial: | none
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | speech

The mark properties allow named markers to be attached to the audio stream. For compatibility with SSML, this must conform to the xsd:token datatype as defined in XML Schema. Synthesis processors must do one or both of the following when encountering a mark:

  • Inform the hosting environment with the value of the mark's name with information allowing the platform to retrieve the corresponding position in the rendered output.
  • When audio output of the SSML document reaches the mark, issue an event that includes the required name attribute of the element. The hosting environment defines the destination of the event.

The mark properties have no audible effect on the speech and instead just serve to mark points in the stream.

Values have the following meanings:

<string>
A string to be used as the name of the mark.

A good way of adding the marking properties could be by means of using the attr() function.

Examples:

h1 {mark-before: "section"}

p {mark-before: attr(id) }

Name: | mark
Value: | [ <'mark-before'> || <'mark-after'> ]
Initial: | not defined for shorthand properties
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | speech

The 'mark' property is a shorthand for setting 'mark-before' and 'mark-after'. If two values are given the first value is 'mark-before' and the second is 'mark-after'. If only one value is given, it applies to both properties.

The following two rules are equivalent:

div {mark-before: "start"; mark-after: "end" }

div {mark: "start" "end" }

10. Voice characteristic properties: 'voice-family', 'voice-rate', 'voice-pitch', 'voice-pitch-range' and 'voice-stress'

Name: | voice-family
Value: | [[<specific-voice> | [<age>] <generic-voice>] [<number>],]* [<specific-voice> | [<age>] <generic-voice>] [<number>] | inherit
Initial: | implementation dependent
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | speech

The value is a comma-separated, prioritized list of voice family names (compare with 'font-family'). Values have the following meanings:

<specific-voice>
Values are specific instances (e.g., comedian, mary, carlos, "valley-girl").
<age>
Possible values are 'child', 'young' and 'old'.
<generic-voice>
Values are voice families. Possible values are 'male', 'female' and 'neutral'.
<number>
Indicates a preferred variant of the other voice characteristics (e.g. the second or next male voice). Possible values are positive integers. '1' is the first of all available voices and is equal to no numeric value.

Examples:

h1 { voice-family: announcer, old male }

p.part.romeo  { voice-family: romeo, young male }

p.part.juliet { voice-family: juliet, female }

p.part.mercutio { voice-family: male 2 }

p.part.tybalt { voice-family: male 3 }

p.part.nurse { voice-family: child female }

Names of specific voices may be quoted, and indeed must be quoted if any of the words that make up the name does not conform to the syntax rules for identifiers [CSS3SYN]. Any whitespace characters before and after the voice name are ignored. For compatibility with SSML, whitespace characters are not permitted within voice names.

The voice-family property is used to guide the selection of the voice to be used for speech synthesis. The overriding priority is to match the language specified by the xml:lang attribute as per the XML 1.0 specification, and as inherited by nested elements until overridden by a further xml:lang attribute.

If there is no voice available for the requested value of xml:lang, the processor should select a voice that is closest to the requested language (e.g. a variant or dialect of the same language). If there are multiple such voices available, the processor should use a voice that best matches the values provided with the voice-volume property. It is an error if there are no such matches.

Name: | voice-rate
Value: | <percentage> | x-slow | slow | medium | fast | x-fast | inherit
Initial: | implementation dependent
Applies to: | all elements
Inherited: | yes
Percentages: | refer to default value
Media: | speech

This property controls the speaking rate. The default rate for a voice depends on the language and dialect and on the personality of the voice. The default rate for a voice should be such that it is experienced as a normal speaking rate for the voice when reading aloud text. Since voices are processor-specific, the default rate will be as well.

<percentage>
Applies to the default speaking rate for each voice. Thus 50% means half the normal rate for this voice.
x-slow, slow, medium, fast and x-fast
A sequence of monotonically non-decreasing speaking rates that are implementation and voice specific.
Name: | voice-pitch
Value: | <number> | <percentage> | x-low | low | medium | high | x-high | inherit
Initial: | medium
Applies to: | all elements
Inherited: | yes
Percentages: | refer to inherited value
Media: | speech

Specifies the average pitch (a frequency) of the speaking voice. The average pitch of a voice depends on the voice family. For example, the average pitch for a standard male voice is around 120Hz, but for a female voice, it's around 210Hz.

Values have the following meanings:

<number>
A positive integer or floating point number that specifies the average pitch of the speaking voice in Hertz.
<percentage>
Specifies a relative change to the inherited value.
x-low, low, medium, high, x-high
A sequence of monotonically non-decreasing pitch levels that are implementation and voice specific.

ISSUE: should we also allow for relative changes in terms of semitones as permitted by SSML?

Name: | voice-pitch-range
Value: | <number> | <percentage> | x-low | low | medium | high | x-high | inherit
Initial: | implementation dependent
Applies to: | all elements
Inherited: | yes
Percentages: | refer to inherited value
Media: | speech

Specifies variation in average pitch. The perceived pitch of a human voice is determined by the fundamental frequency and typically has a value of 120Hz for a male voice and 210Hz for a female voice. Human languages are spoken with varying inflection and pitch; these variations convey additional meaning and emphasis. Thus, a highly animated voice, i.e., one that is heavily inflected, displays a high pitch range. This property specifies the range over which these variations occur, i.e., how much the fundamental frequency may deviate from the average pitch.

Values have the following meanings:

<number>
An non-negative integer or floating point number indicating pitch range in Hertz. Low ranges produce a flat, monotonic voice. A high range produces animated voices.
<percentage>
Specifies a relative change to the inherited value.
x-low, low, medium, high and x-high
A sequence of monotonically non-decreasing pitch ranges that are implementation and language dependent.

ISSUE: should we also allow for relative changes in terms of semitones as permitted by SSML?

Name: | voice-stress
Value: | strong | moderate | none | reduced | inherit
Initial: | moderate
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | speech

Indicates the strength of emphasis to be applied. Emphasis is indicated using a combination of pitch change, timing changes, loudness and other acoustic differences) that varies from one language to the next.

Values have the following meanings:

none, moderate and strong
These are monotonically non-decreasing in strength, with the precise meanings dependent on language being spoken. The value 'none' inhibits the synthesizer from emphasizing words it would normally emphasize.
reduced
Effectively the opposite of emphasizing a word. For example, when the phrase "going to" is reduced it may be spoken as "gonna".

11. Duration property: 'voice-duration'

Name: | voice-duration
Value: | <time>
Initial: | implementation dependent
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | speech

Allows authors to specify how long it should take to render the selected element's content. This property overrides the 'voice-rate' property. Values have the following meanings:

<time>

Specifies a value in seconds or milliseconds for the desired time to take to speak the element contents, for instance, "250ms", or "3s". Only positive numbers are allowed.

12. Phonetics: 'phonemes', '@phonetic-alphabet' and 'content'

Name: | phonemes
Value: | <string>
Initial: | implementation dependent
Applies to: | all elements
Inherited: | no
Percentages: | N/A
Media: | speech

This allows authors to specify a phonetic pronunciation for the text contained by the corresponding element.

@phonetic-alphabet

The default alphabet for the pronunciation string of the 'phonemes' property is the International Phonetic Alphabet ("ipa"), corresponding to Unicode representations of the phonetic characters developed by the International Phonetic Association [IPA]. The phonetic alphabet can be explicitly specified using the @phonetic-alphabet rule, for instance:

Example:

@phonetic-alphabet "ipa";
#tomato { phonemes: "t\0252 m\0251 to\028a " }

This will direct the speech synthesizer to replace the default pronunciation by the corresponding sequence of phonemes in the designated alphabet.

At most one @phonetic-alphabet rule may appear in style sheet and it must appear, when used, before any occurrence of the 'phonemes' property.

ISSUE: we do not mention any other possible value for @phonetic-alphabet. SSML 1.0 defines "ipa" to be the only valid value - any other value should be added with the "x-" prefix. Do we want to follow this? Or do we allow some other values? SAMPA comes to my mind as a widely used ASCII alternative to IPA, but then: SAMPA is language dependent, and it might be better to have X-SAMPA.

Inserted and replaced content

Sometimes, authors will want to specify a mapping from the source text into another string prior to the application of the regular pronunciation rules. This may be used for uncommon abbreviations or acronyms which are unlikely to be recognized by the synthesizer. The 'content' property can be used to replace one string by another. In the following example, the abbreviation is rendered using the content of the title attribute instead of the element's content:

Example:

abbr { content: attr(title); }
  ...

<abbr title="World Wide Web Consortium">W3C</abbr>

This replaces the content of the selected element by the string "World Wide Web Consortium".

In a similar way text-to-speach strings in a document can be replaced by a previously recorded version:

Example:

.hamlet { content: url(gielgud.wav); }
  ...

<div class="hamlet">
To be, or not to be: that is the question:
</div>

If the format is supported, the file is available and the UA is configured to do so, a recording of Sir John Gielgud's declamation of the famous monologue will be played, otherwise the UA falls back to render the text-to-speech with its own synthesizer.

Furthermore authors, or users in a user stylesheet, may want to add some information to ease understanding the structure for non-visual interaction with the document. They can do so by using the '::before' and '::after' pseudo-elements that will be inserted between the element's contents and the 'rest':

Example:

ul::before { content: "Start list: " }
ul::after  { content: "List end. " }
li::before { content: "List item: " }

This inserts the string "Start list: " before a list and the string "List item: " before each list item; likewise the string "List end: " inserted after the list will inform the user that the list is finished.

Different stylesheets can be used to define the level of verbosity for additional information spoken by screen readers.

Detailed information can be found in the CSS3 Generated and Replaced Content Module [CSS3GENCON].

Editor's note: The alphabet is specified via an at-rule to avoid problems with inappropriate cascades that can occur if the alphabet was set via a property.

ISSUE: should there be a CSS equivalent to the SSML <sub> element? This gives the author the means to replace one string with another as means to changing how something is spoken, e.g. "as-key" for "ASCII". A possible solution is a new CSS property 'say-instead' for instance:

   say-instead: "as-key";

The drawback with this property is that it has to be applied to a specific instance of an element and can't be used more generally. In the longer term, the use of pronunciaton lexicons would provide a better solution.

Appendix A - Changes from previous draft

The main changes have been to align the definitions with the latest version of SSML as it reached W3C Recommendation status. This effects voice-volume, voice-rate, voice-pitch, voice-pitch-range, and voice-stress, where the enumerated logical values are now defined as monotonically non-decreasing sequences to match SSML. Named relative values such as louder and softer have been dropped since they are not supported by SSML and can't be related through percentage changes to the enumeration of logical values.

General overhaul to bring it in line with other CSS3 modules

The aural "box" model has been added.

Definitions of the values for the voice-volume property have been slighly refined.

The 'pause' properties have been re-defined as to represent the break between one element and the next one, outside the cues. Also, pause collapsing has been explicitly defined.

The new properties 'rest-before', 'rest-after' and the shorthand 'rest' have been added.

The cue properties have been modified to allow the cue volume to be set independently or relative to that of synthetic speech.

The mark-before, mark-after and mark properties have been introduced to take advantage of SSML's mark feature, which is often used for rewinding back to a marked point in an audio stream.

Definition of @phonetic-alphabet has been re-worded.

The interpret-as property has been temporarily dropped until the Voice Browser working group has further progressed work on the SSML <say-as> element.

References and Property index have been added

Appendix B - Profiles

TBD

Appendix C - Acknowledgements

The editors would like to thank the members of the W3C Voice Browser and Cascading Style Sheets working groups for their assistance in preparing this new draft. Special thanks to Ellen Eide (IBM) for her detailed comments.

Appendix D - References

Normative references

[CSS3CASCADE]
Håkon Wium Lie. CSS3 module: Cascading and inheritance, W3C Working Draft 19 February 2002 (Work in progress). URL: http://www.w3.org/TR/2002/WD-css3-cascade-20020219
[CSS3TABLES]
Bert Bos. CSS3 module: Tables, (forthcoming), W3C working draft (Work in progress).
[CSS3SYN]
L. David Baron; et al. CSS3 module: Syntax, W3C Working Draft 13 August 2003 (Work in progress). URL: http://www.w3.org/TR/2003/WD-css3-syntax-20030813
[CSS3VAL]
Håkon Wium Lie; Chris Lilley. CSS3 module: Values and Units, W3C Working Draft, 13 July 2001 (Work in progress). URL: http://www.w3.org/TR/2001/WD-css3-values-20010713

Informative references

[CSS3BOX]
Bert Bos. CSS3 module: The box model, W3C Working Draft 24 October 2002. URL: http://www.w3.org/TR/2002/WD-css3-box-20021024
[CSS3GENCON]
Ian Hickson. CSS3 Generated and Replaced Content Module, W3C Working Draft 14 May 2003. URL: http://www.w3.org/TR/2003/WD-css3-content-20030514
[IPA]
International Phonetic Association. See http://www.arts.gla.ac.uk/ipa/ipa.html for the organization's website.
[SELECT]
Daniel Glazman; Tantek Çelik; Ian Hickson; et al. Selectors, W3C Candidate Recommendation 13 November 2001. URL: http://www.w3.org/TR/2001/CR-css3-selectors-20011113
[SSML10]
Daniel C. Burnett, Mark R. Walker, Andrew Hunt; Speech Synthesis Markup Language (SSML) Version 1.0, W3C Recommendation 7 September 2004. URL: http://www.w3.org/TR/2004/REC-speech-synthesis-20040907/

Appendix E - Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
voice-volume | <number> | <percentage> | silent | x-soft | soft | medium | loud | x-loud | inherit | medium | all elements | yes | refer to inherited value | speech
voice-balance | <number> | left | center | right | leftwards | rightwards | inherit | center | all elements | yes | N/A | speech
speak | none | normal | spell-out | digits | literal-punctuation | no-punctuation | inherit | normal | all elements | yes | N/A | speech
pause-before, pause-after | <time> | none | x-weak | weak | medium | strong | x-strong | inherit | implementation dependent | all elements | no | N/A | speech
pause | [ <'pause-before'> || <'pause-after'> ] | inherit | implementation dependent | all elements | no | N/A | speech
rest-before, rest-after | <time> | none | x-weak | weak | medium | strong | x-strong | inherit | implementation dependent | all elements | no | N/A | speech
rest | [ <'rest-before'> || <'rest-after'> ] | inherit | implementation dependent | all elements | no | N/A | speech
cue-before, cue-after | <uri> [<number> | <percentage> | silent | x-soft | soft | medium | loud | x-loud] | none | inherit | none | all elements | no | apply to inherited value for voice-volume | speech
cue | [ <'cue-before'> || <'cue-after'> ] | inherit | not defined for shorthand properties | all elements | no | apply to inherited value for voice-volume | speech
mark-before, mark-after | <string> | none | all elements | no | N/A | speech
mark | [ <'mark-before'> || <'mark-after'> ] | not defined for shorthand properties | all elements | no | N/A | speech
voice-family | [[<specific-voice> | [<age>] <generic-voice>] [<number>],]* [<specific-voice> | [<age>] <generic-voice>] [<number>] | inherit | implementation dependent | all elements | yes | N/A | speech
voice-rate | <percentage> | x-slow | slow | medium | fast | x-fast | inherit | implementation dependent | all elements | yes | refer to default value | speech
voice-pitch | <number> | <percentage> | x-low | low | medium | high | x-high | inherit | medium | all elements | yes | refer to inherited value | speech
voice-pitch-range | <number> | x-low | low | medium | high | x-high | inherit | implementation dependent | all elements | yes | refer to inherited value | speech
voice-stress | strong | moderate | none | reduced | inherit | moderate | all elements | yes | N/A | speech
voice-duration | <time> | implementation dependent | all elements | no | N/A | speech
phonemes | <string> | implementation dependent | all elements | no | N/A | speech

The following properties are defined in other modules:

  • content [CSS3GENCON]
  • display [CSS3BOX]


CSS3 Template Layout Module

CSS Template Layout Module

W3C Working Draft 29 April 2010

This version:
http://www.w3.org/TR/2010/WD-css3-layout-20100429
Latest version:
http://www.w3.org/TR/css3-layout
Previous version:
http://www.w3.org/TR/2009/WD-css3-layout-20090402
Editors:
Bert Bos (W3C) bert@w3.org
César Acebal (University of Oviedo)

Copyright © 2010 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

Image: four elements move to four slots in a template

A grid with four slots defined by ‘display: "aaaaaaa" "bccccdd"’.

CSS is a simple, declarative language for creating style sheets that specify the rendering of HTML and other structured documents. This specification is part of level 3 of CSS (“CSS3”) and contains features to describe layouts at a high level, meant for tasks such as the positioning and alignment of “widgets” in a graphical user interface or the layout grid for a page or a window, in particular when the desired visual order is different from the order of the elements in the source document. Other CSS3 modules contain properties to specify fonts, colors, text alignment, list numbering, tables, etc.

The features in this module are described together for easier reading, but are usually not implemented as a group. CSS3 modules often depend on other modules or contain features for several media types. Implementers should look at the various “profiles” of CSS, which list consistent sets of features for each type of media.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css3-layout” in the subject, preferably like this: “[css3-layout] …summary of comment…”

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Changes from the previous draft, apart from editorial changes, include: a clarification about using the (proposed) ‘gr’ unit inside a template specification; the definition of the intrinsic height of a ‘.’ slot; and the addition of an open issue about setting writing modes on individual slots.

This draft is related to the drafts about positoning with grid units (‘gr’) [CSS3GRID], flexible GUIs [CSS3-FLEXBOX], and tables [CSS3TBL]. The CSS Working Group is considering combining some or all of these into a single specification with all matrix-based layouts.

The section on “CR exit criteria” lists some conditions for this specification to become a W3C Recommendation.

Table of contents

  • 1 Dependencies on other modules
  • 2 Introduction
  • 3 Declaring templates: the ‘display’ property
  • 4 Computing the width of the slots
  • 5 Computing the height of the slots
  • 6 Flowing content into the template: the ‘position’ property
  • 7 The ‘::slot()’ pseudo-elements
  • 8 Vertical alignment
  • 9 Page-based templates and other templates in paged media
  • 10 Stacking order
  • 11 Floating elements inside templates
  • 12 Definition of the ‘gr’ unit in a template element
  • 13 CR exit criteria
  • 14 History
  • Acknowledgments
  • References
  • Index

1 Dependencies on other modules

This CSS3 module depends on the following other CSS3 modules:

  • CSS syntax module [CSS3SYN] – interactive vs non-interactive media.
  • CSS values and Units module [CSS3VAL] – <string> and <length>.
  • CSS box module [CSS3BOX] – properties width, height, float, display and overflow
  • CSS text layout [CSS3TEXTLAYOUT] – properties direction and block-flow
  • CSS positioning [CSS3POS] – property z-index
  • CSS paged media [CSS3PAGE] – properties page-break-before, page-break-after and page; page area (in particular its width & height).
  • CSS background and borders [CSS3BG] – property background and box-shadow?
  • CSS tables [CSS3TBL] – property vertical-align. [or Box Module?]

It has non-normative (informative) references to the following other CSS3 modules:

  • Selectors [SELECT]

See section 1.4.2 of CSS level 2 [CSS21] for the grammar and other notations that this specification uses in property definitions.

2 Introduction

(This section is not normative.)

Image: four elements move to four slots in a template

Four regions, called a, b, c and d, each receive a part of a document

The styling of a Web page, a form or a graphical user interface can roughly be divided in two parts: (1) defining the overall “grid” of the page or window and (2) specifying the fonts, indents, colors, etc., of the text and other objects. The two are not completely separate, of course, because indenting or coloring a text influences the perceived grid as well. Nevertheless, when one separates the parts of a style that should change when the window gets bigger from the parts that stay the same, one often finds that the grid changes (room for a sidebar, extra navigation bar, big margins, larger images…), while fonts, colors, indents, numbering styles, and many other things don't have to change, until the size of the window becomes extreme.

The properties in this specification work by associating a layout policy with an element. Rather than letting an element lay out its descendants in their normal order as inline text or as blocks of text (the policies available in CSS level 1), the policy defined in this module, called template-based positioning, gives an element an invisible grid for aligning descendant elements.

Because layouts on the Web have to adapt to different window and paper sizes, the rows and columns of the grid can be made fixed or flexible in size.

The typical use cases for these properties include:

  • Complex Web pages, with multiple navigation bars in fixed positions, areas for advertisements, etc.
  • Complex forms, where the alignment of labels and form fields may be easier with the properties of this module than with the properties for tables and margins.
  • GUIs, where buttons, toolbars, labels, icons, etc., are aligned in complex ways and have to stay aligned (and not wrap, for example) when the window is resized.
  • Paged displays (e.g., printed media) where each page is divided in fixed areas for different kinds of content.

Template-based positioning is an alternative to absolute positioning, which, like absolute positioning, is especially useful for aligning elements that don't have simple relationships in the source (parent-child, ancestor-descendant, immediate sibling). But in contrast to absolute positioning, the elements are not positioned with the help of horizontal and vertical coordinates, but by mapping them into slots in a table-like template. The relative size and alignment of elements is thus governed implicitly by the rows and columns of the template. A template doesn't allow elements to overlap, but it provides layouts that adapt better to different widths.

The mapping is done with the ‘position’ property, which specifies in this case into which slot of the template the element goes. The template itself is specified on the ‘display’ property of some ancestor of the elements to remap.

In this example, the four children of an element are assigned to four slots (called a, b, c and d) in a 2×2 template. (All mark-up examples in this specification are HTML fragments, unless otherwise stated.)

Image: sample rendering

Each element occupies one slot. In this template, all slots have the same size.

<style type="text/css">
  dl { display: "ab"
                "cd" }
  #sym1 { position: a }
  #lab1 { position: b }
  #sym2 { position: c }
  #lab2 { position: d }
</style>
<dl>
  <dt id=sym1>A
  <dd id=lab1>A is een aapje
  <dt id=sym2>B
  <dd id=lab2>B is de bakker
</dl>

Templates can also help with device-independence. This example uses Media Queries [MEDIAQ] to change the overall layout of a page from 3-column layout for a wide screen to a 1-column layout for a narrow screen. It assumes the page has been marked-up with logical sections with IDs.

@media all
{
  body { display: "aaa"
                  "bcd" }
  #head { position: a }
  #nav { position: b }
  #adv { position: c }
  #body { position: d }
}
@media all and (max-width: 500px)
{
  body { display: "a"
                  "b"
                  "c" }
  #head { position: a }
  #nav { position: b }
  #adv { display: none }
  #body { position: c }
}

Elements can be positioned this way, but not made to overlap, unless with negative margins. Here is how the “zunflower” design of the Zen Garden could be done:

#container { display: "abc" }
#intro { position: a; margin-right: -2em; box-shadow: 0.5em 0.5em 0.5em }
#supportingText { position: b; box-shadow: 0.5em 0.5em 0.5em }
#linkList { position: c }

Template-based positioning borrows some concepts from table layout, in particular the idea of aligning elements in rows and columns, so that they constrain each other's size. But there are also differences. This example shows some of them. Assume this document fragment:

<div class=group>
 <div>aa aa aa aa aa aa</div>
 <div>bbb</div>
 <div class=menu>ccccc</div>
</div>

We can lay it out as three columns, as the following illustrations show. The style sheet would contain the following.

.group {display: table}
.group > div {display: table-cell}

[Three unequal cells]

Example of rendering with a table.

We can also use a template, in which case the style sheet would contain this:

.group {display: "abc"}
.group > div {position: a}
.group > div + div {position: b}
.group > div + div + div {position: c}

By default, the table is as wide as needed to fit its contents. To make sure it is as wide as its containing block, we need to add

.group {display: table; width: 100%}

That is not needed for the template, but, on the other hand, if we want the template to fit its contents, we would need to say so:

.group {display: "abc"; width: fit-content}

(See [CSS3BOX] for the definition of the ‘width’ property.) The columns of the template are by default all the same size. The columns of the table satisfy certain constraints, but the exact size is not defined. We can make them all the same by adding a rule (see [CSS3TBL]):

.group {display: table; width: 100%; table-layout: fixed}

[Three equal cells]

Example of rendering with equal columns.

In both styles, we can set a column to a certain size:

div.menu {width: 3em}

resp.,

.group {display: "abc" * * 3em}

[Two equal cells, third is 3em wide]

Example of rendering with a fixed third column and the other two columns of equal width.

If there is an unknown number of columns (children of the div.group element), the style sheet for the table model will automatically take them into account. The style sheet for the template model, however, creates a template of exactly three columns and can't handle tables with an unknown number of columns. The extra elements will be added into the default slot (in this case the ‘a’ slot).

In both models, elements can have borders, but only in the table model can borders be collapsed, which makes setting borders a little easier in the table model:

.group {display: table; border-collapse: collapse}
.group > div {border: solid}

resp.,

.group > div {border: solid; border-left: none}
.group > div:first-child {border-left: solid}

In the template model, the order of the elements is explicit, and thus it is possible to reverse the order of the columns:

.group > div {position: c}
.group > div + div {position: b}
.group > div + div + div {position: a}

[Different contents for the cells]

Example of rendering with the contents of the three columns reversed: the third element is shown in the first slot and the first element in the third slot.

In the table model, the order of the rows and columns is given by the document source and thus can't be changed.

This example shows a way to move notes to the end of a section. “Notes” in this example refers to elements in HTML with a class of “note”. A fragment of HTML such as

<div class=section>
  <p>The balubious coster of the fifth secter<span
    class=note> The sixth secter coster is a difter
    manon.</span> of The Rollow Carpug mentizes a costernica.
  <p>…
</div>

with this style sheet

div.section {
    display: "@" available
             "F" available}
.note {
    position: F;
    content: counter(note) ".\A0" contents;
    counter-increment: note;
    font-size: smaller}
.note::before {
    content: counter(note);
    position: @;
    vertical-align: super;
    font-size: larger}

results in a rendering similar to this:

Same text, with the SPAN replaced by “(1)” and it content moved to the end.

Rendering of a text with footnotes.

3 Declaring templates: the ‘display’ property

Name: | display
New value: | inline? [ <string> [ / <row-height> ]? ]+ <col-width>*
Percentages: | N/A
Computed value: | specified value

An element with this ‘display’ is similar to a table element, in that its content is laid out in rows and columns. The two main differences are that the number of rows and columns doesn't depend on the content, but is fixed by the value of the property; and that the order of the descendants in the source document may be different from the order in which they appear in the rendered template.

If the keyword ‘inline’ is present, the element is an inline-level element, otherwise it is a block-level element [CSS3BOX].

Note that ‘display’ is extended to apply to ‘@page’ rules as well and that it has a different default there, viz., ‘"@"’. See “Templates in paged media” below.

Each string consist of one or more letters (see <letter> below), at signs (“@”), periods (“.”) and spaces. Each string represents one row in the template, each character other than a space represents one column in that row. Spaces have no meaning. They may be added for readability.

The symbols in the template have the following meaning

a letter
slot for content.
@
(at sign) default slot for content.
.
(period) white-space.

Multiple identical letters in adjacent rows or columns form a single slot that spans those rows and columns. Ditto for multiple “@”s. Uppercase and lowercase are considered to be the same letter (i.e., the template is case-insensitive).

Non-rectangular slots and multiple slots with the same letter are illegal. A template without any letter or “@” is illegal. A template with more than one “@” slot is illegal. These errors cause the declaration to be ignored.

Note: non-rectangular and disconnected regions may be permitted in a future update of CSS.

Rows with fewer columns than other rows are implicitly padded with periods (“.”) (that will thus not contain any elements).

Each slot (letter or “@”) acts as a block element for its contents.

Each <row-height> sets the height of the preceding row. The default is ‘auto’. The values can be as follows:

<length>
An explicit height for that row. Negative values make the template illegal. If the length is expressed in ‘gr’ units, these refer to the inherited grid, not the grid defined by the template itself (see “Definition of the ‘gr’ unit in a template element”).
auto
The row's height is determined by its contents. See the algorithm below.
*
(asterisk) All rows with an asterisk will be of equal height. See the algorithm below.

Each <col-width> sets the width of a column. If there are more <col-width>s then columns, the last ones are ignored. If there are fewer, the missing ones are assumed to be ‘*’. Each <col-width> can be one of the following:

<length>
An explicit width for that column. Negative values make the template illegal.
*
(asterisk.) All columns with a ‘*’ have the same width. See the algorithm below.
max-content,
min-content
The column's width is determined by its contents. See the algorithm below.
minmax(p,q)
The column's width is constrained to be greater than or equal to p and less than or equal to q. p and q stand for [ <length> | max-content | min-content | * ]. There may be white space around the p and q. If q < p, then q is ignored and ‘minmax(p,q)’ is treated as ‘minmax(p,p)’.
fit-content
Equivalent to ‘minmax(min-content, max-content)’.

Note that it is legal to specify no widths at all. In that case, all columns have the same width.

The orientation of the template is independent of the writing mode (‘direction’ and ‘block-flow’ properties): the first string is the topmost row and the first symbol in each string is the leftmost column.

<style type="text/css">
  div { display: ".aa..bb." }
  p.left { position: a }
  p.right { position: b }
</style>
<div>
  <p class=left>Left column
  <p class=right>Right column
</div>

An element with a template value for its ‘display’ property is called a template element. An element's template ancestor is defined (recursively) as follows:

  • if the element has ‘position: fixed’, ‘position: absolute’, a value of ‘float’ that is not ‘none’ or the element is the root element, than it has no template ancestor.
  • else, if the element's parent has a template as its ‘display’, then that parent is the element's template ancestor.
  • else, the element's template ancestor is the same as its parent's template ancestor.

4 Computing the width of the slots

First, the intrinsic minimum and intrinsic preferred widths are defined as follows:

  • A column with a <col-width> of a given <length> has intrinsic minimum and intrinsic preferred widths both equal to that <length>.

  • A column with a <col-width> of ‘*’ has an infinite intrinsic preferred width. Its intrinsic minimum width is 0.

  • A column with a <col-width> of ‘min-content’ has an intrinsic minimum width and intrinsic preferred width that are both equal to the largest of the intrinsic minimum widths of all the slots in that column:

    • The intrinsic minimum width of a “.” is 0.
    • The intrinsic minimum width of a letter or “@” is 0 if that slot spans two or more columns; otherwise, it is the intrinsic minimum width as defined by [CSS3BOX]. For the purpose of that definition, the slot is considered as a block with a ‘block-flow’ of ‘tb’ with its contents as its children. Should the block progression direction be a property?

  • A column with a <col-width> of ‘max-content’ has an intrinsic minimum width and intrinsic preferred width that are both equal to the largest of the intrinsic preferred widths of all the slots in that column:

    • The intrinsic preferred width of a “.” is 0.
    • The intrinsic preferred width of a letter or “@” is the intrinsic preferred width as defined by [CSS3BOX]. For the purpose of that definition, the slot (which may span several columns) is considered as a block with a ‘block-flow’ of ‘tb’ with its contents as its children. Should the block progression direction be a property?

  • A column with a <col-width> of ‘minmax(p,q)’ has an intrinsic minimum width equal to p and an intrinsic preferred width equal to q.

Next, the layout algorithm distinguishes between elements with and without an a-priori known content width.

The width isn't known a-priori, if, e.g., ‘width’ is ‘auto’ and the element is floating, absolutely positioned, inline-block or a child of a block with vertical writing mode.

  • If the element has an a-priori width:

    • If the sum of the intrinsic minimum widths of the columns is larger than the element's width, each column is set to its intrinsic minimum width and the contents will overflow (see ‘overflow’).
    • If the sum of the intrinsic minimum widths of the columns is less than or equal to the element's width, the columns are widened until the total width is equal to the element's width, as follows: all columns get the same width, except that no column or span of columns may be wider than its intrinsic preferred width. If the columns cannot be widened enough, the template is left or right aligned in the element's content area, depending on whether ‘direction’ is ‘ltr’ or ‘rtl’, respectively.

    Note: In a future update of CSS, columns might get a property to allow them some flexibility to become wider than their intrinsic preferred width under certain conditions or by a certain amount.

  • If the element doesn't have an a-priori width:

    • If the sum of the intrinsic minimum widths of the columns is wider than the initial containing block, each column is set to its intrinsic minimum width. The element's used width is the sum of the widths of the columns.
    • If the sum of the intrinsic minimum widths of the columns is less than or equal to the width of the initial containing block, the columns are widened until the total width is equal to the initial containing block, as follows: all columns get the same width, except that no column or span of columns may be wider than its maximum intrinsic width. The element's used width is the sum of the widths of the columns.

An extra step may be necessary in paged media if a page break occurs inside a template (only in the case of an element-based template, see below). If the template, after computing the width and height, is too big to fit on the current page, and if a suitable break point exists, the part of the template after that break point is put on the next page. The width of the containing block on that page may be different if that page has different margins from the current page (see [CSS3PAGE]) and thus the width and height of that part of the template must be recalculated in the new context.

Note that the widths of the columns can be completely determined before laying out any of the contents as long as there are no columns with a <col-width> of ‘min-content’ or ‘max-content’.

5 Computing the height of the slots

The height of the template is the smallest possible under the following constraints:

  1. Rows with a height set to <length> have that height.
  2. No row has a negative height.
  3. All rows with a height set to ‘*’ are the same height.
  4. Every sequence of one or more rows of which at least one has a height set to ‘auto’ is at least as high as every letter or “@” slot that spans exactly that sequence of rows.
  5. If the computed value of the element's ‘height’ is ‘auto’, then every sequence of one or more rows of which at least one has a height set to ‘*’ is at least as high as every letter or “@” slot that spans exactly that sequence of rows.
  6. The whole template is at least as high as the computed value of the element's ‘height’, unless that value is ‘auto’, or unless all rows have a height set to <length>.

If the template is higher than the element's ‘height’, the element overflows, see ‘overflow’.

Note: In a future update of CSS, rows might get a property to specify how the height of that row is adjusted in case the above calculation yields a template that is less tall than the element itself.

The height of a slot is measured as if the slot had one anonymous block as a child that contains all the slot's contents, and both the slot and the anonymous block have a ‘block-flow’ of ‘tb’ and the anonymous block's height is computed as a flow root (see “Auto heights for flow roots” in [CSS3BOX]). Roughly, this means the height is from the top margin edge of the topmost element to the bottom margin edge of the bottommost element or of the bottommost float. Should the block progression direction be a property?

The intrinsic height of a ‘.’ slot is 0.

This example divides the window in three rows and three columns, separated by 1em of white space. The middle row and the middle column are flexible, the others are fixed at a specific size. The first column is 5em wide, the last one 10em.

<style type="text/css">
  body {
    height: 100%;
    display: "a   .   b   .   c"  /2em
             ".   .   .   .   ."  /1em
             "d   .   e   .   f"
             ".   .   .   .   ."  /1em
             "g   .   h   .   i"  /2em
             5em 1em  *  1em 10em}
  #logo {position: a}
  #motto {position: b}
  #date {position: c}
  #main {position: e}
  #adv {position: f}
  #copy {position: g}
  #about {position: h}
</style>
<p id=logo><img src=...
<p id=motto>Making Web pages since 1862
<p id=date>August 2, 2004
...

[Add example with three columns, first two as narrow as possible, third one taking up all remaining space.]

6 Flowing content into the template: the ‘position’ property

Name: | position
New value: | <letter> | same
Percentages: | N/A
Computed value: | ‘<letter>’ or ‘static’; see text

This value of the ‘position’ property specifies into which row and column of a template the element is placed. The <letter> must be a single letter, with category Lu, Ll or Lt in Unicode [UNICODE]), or a “@” symbol.

<letter>
The element is taken out of the flow of its parent and put into the specified slot in its template ancestor. If there is no slot of that name, the computed value is ‘static’.
same
A value of ‘same’ instead of a letter computes to the same letter as the most recent element with a letter as position that has the same template ancestor. If there is no such element, the value computes to ‘static’.

The containing block of an element with one of these values for ‘position’ is the slot in the template into which it is flowed.

Multiple elements may be put into the same slot. They will be laid-out according to their ‘display’ property in the order they occur in the source document.

The content of a template element is put in the slot marked with “@”s. If there is no such slot, the content is put in the first (leftmost) slot on the first row that doesn't consist of only “.”.

POWERED BY HeroNote

A common markup in HTML for illustrations with captions is as follows:

<div class=figure>
 <p><img src="paul.jpg" alt="...">
 <p class=caption>A pond in a playground in Amsterdam
</div>

The caption can be put above the image by using a template as follows:

div.figure {display: "aaa"
                     ".b."
                     * min-content *}
div.figure p {position: b}
div.figure p.caption {position: a; text-align: center}

The caption can be wider than the image and the image will be centered.

When the figure is floating, it is probably better to not let the caption become wider than the image (unless the caption cannot be made narrow enough):

div.figure {float: right; display: "a" "b" min-content}
div.figure p {position: b}
div.figure p.caption {position: a; text-align: center}

In this example, a form is laid out on a grid, with two labels and two input boxes and a submit and a reset button:

form {
  border: thin solid;
  display: "aaaa.bbbb"
           "........."/1em
           "cccc.dddd"
           "........."/1em
           "...ee..ff" }
label[for=minv] { position: a }
input#minv { position: b; display: block }
label[for=maxv] { position: c }
input#maxv { position: d; display: block }
input[type=submit] { position: e; display: block }
input[type=reset] { position: f; display: block }

Here is the fragment of HTML that the style is applied to:

<form action="./">
  <label for=minv>Enter minimum value:</label>
  <input id=minv name=minv>
  <label for=maxv>Enter maximum value:</label>
  <input id=maxv name=maxv>
  <input type=submit value="OK">
  <input type=reset value="Reset">
</form>

The addition of ‘display: block’ causes the form controls to use the width computation of blocks, in other words: they will be as wide as their containing block, which in this case means that they will be as wide as the slot they are assigned to. Without it, they would be inline elements and just be left-aligned in their slots.

Image simulating the layout of the example

Possible rendering of the example.

This example shows that templates can be nested. The body has two columns. The #content element that goes into the second column has itself another template, into which the various “modules” are placed.

[Screendump with nested templates]

Possible rendering of the nested templates. (The borders are added for clarity, they don't occur in the style rules below. The red border is the inner template.)

For clarity, the inner template uses different letters for the slots than the outer template. This is not required.

<style type="text/css">
body {
     display: "a   b"
              10em *;
}
#nav {
     position: a;
}
#content {
     position: b;
     display: "c   .   d   .   e   "
              ".   .   .   .   .   "/1em
              ".   .   f   .   .   "
               *  1em  *  1em  *;
}
.module.news {
     position: c;
}
.module.sports {
     position: d;
}
.module.personal {
     position: e;
}
#foot {
     position: f;
}
</style>
<body>
<ul id="nav">
     <li>navigation</li>
</ul>
<div id="content">
    <div class="module news">
         <h3>Weather</h3>
         <p>There will be weather</p>
    </div>
    <div class="module sports">
         <h3>Football</h3>
         <p>People like football.</p>
    </div>
    <div class="module sports">
         <h3>Chess</h3>
         <p>There was a brawl at the chess tournament</p>
    </div>
    <div class="module personal">
         <h3>Your Horoscope</h3>
         <p>You're going to die (eventually).</p>
    </div>
    <p id="foot">Copyright some folks</p>
</div>

</body>

This example shows the use of ‘same’ to put DD elements in the same slot as the preceding DT.

...
DL {display: "a.b.c"  * 2em * 2em *}
DT.mineral {position: a}
DT.animal {position: b}
DT.plant {position: c}
DD {position: same; margin-left: 1em}
...
<DL>
 <DT class=animal>falcon
 <DD>This bird of prey...
 <DT class=animal>rabbit
 <DD>Local restaurants...
 <DT class=mineral>granite
 <DD>This rock occurs...
 <DT class=plant>olive
 <DD>The fruit of...
 <DT class=mineral>limestone
 <DD>A rock composed of...
 <DT class=plant>pine
 <DD>The western half...
</DL>

Possible rendering of the DL list, with items sorted into three columns.

7 The ‘::slot()’ pseudo-elements

The slots of a template element can be individually addressed with the ‘slot()’ pseudo-element.

For example, the following sets the color and vertical alignment of some of the slots in a template:

body { display: "aaa"
                "bcd" }
body::slot(b) { background: #FF0 }
body::slot(c), body::slot(d) { vertical-align: bottom }

A ‘::slot(X)’ pseudo-element selects the slot with name X (a letter or “@”) of the subject of a selector. If that subject is not a template element, or if it has no such slot, the pseudo-element selects nothing. (I.e., these cases are legal selectors, they just happen to match nothing.)

Only the following properties apply to the ‘slot()’ pseudo-element:

  • All background-* properties (including the ‘background’ shorthand).
  • ‘vertical-align’
  • The ‘overflow’ property.
  • The ‘block-flow’ and ‘direction’ properties?
  • The ‘box-shadow’ property?

The background of a slot is drawn immediately on top of the background of the template element itself.

8 Vertical alignment

The ‘vertical-align’ property of a ‘::slot()’ pseudo-element can be used to align elements vertically in a slot. The effect is as if the hypothetical anonymous block that contains the slot's contents is positioned as follows:

bottom
The content of the slot is aligned to the bottom of the slot: the bottom margin edge of the anonymous block coincides with the bottom of the slot.
middle
The content of the slot is vertically centered in the slot: the distance between the top margin edge of the anonymous block and the top of the slot is equal to the distance between the bottom margin edge of the anonymous block and the bottom of the slot. (Note that if the content overflows the slot, it will overflow both at the top and at the bottom.)
baseline
The anonymous block that encloses the content is placed as high as possible under two constraints:
  1. The top margin edge of the anonymous block may not be higher than the top edge of the slot.
  2. The topmost baseline in the content may not be higher than the topmost baseline of content in any other slot in the same row that also has ‘vertical-align: baseline’. Baselines of content inside floats are not taken into account. Slots that span several rows are considered to occur in their topmost row.

For all other values, the content is top aligned: the top margin edge of the anonymous box coincides with the top edge of the slot.

9 Page-based templates and other templates in paged media

A template can also be attached to a page, rather than an element. Such a template is called a page-based template as opposed to an element-based template.

The difference between page-based layout templates and element-based ones is that the size of a slot in a page-based layout template only depends on the template and the page size, never on the intrinsic size of the content.

Another difference is that content that overflows a slot may cause a page break: the rest of the content is put on another page. See below.

The syntax of a page-based template is the same as that of an element-based one, but the declaration appears in an ‘@page’ rule and any <col-width> or <row-height> that is neither ‘*’ nor a <length> is treated as if it were ‘*’.

Although the occurrence of keywords, such as ‘fit-content’ or ‘auto’, is valid and well defined, a UA, especially an editor, may want to issue a warning, because those keywords don't have any useful function in page-based templates.

@page :first { display: "abc" "def" }
@page { display: "def" }

body {position: e}
h1 {position: b}

The default ‘display’ value of a page is ‘display: "@"’.

The following rule is typically not needed, because it is the default:

@page { display: "@" }

The height of the slots in a template is computed as in the section “Computing the height of the slots,” except that the page area's height [CSS3PAGE] is used instead of the element's height. Similarly, the width of the slots is computed as in the section “Computing the width of the slots,” but with the page area's width replacing the element's width.

Note that certain rules in those sections are never applied, because the page area's width and height are always known a-priori and the width and height of slots is always a <length> or ‘*’.

If a slot of a page-based template on non-interactive media has an ‘overflow’ property of ‘visible’, then content that overflows that slot in the block progression direction (i.e., below the slot in the case of horizontal text) causes a page break and is continued on the next page. [What happens in non-interactive media with an ‘overflow’ of ‘scroll’ or ‘auto’?]

For page breaking purposes, each slot is considered as a page and the page break properties on the elements in that slot determine where the content for that slot is broken. Content after the page break is put in the slot of the same name on the next page that has such a slot. If there is no such page the content after the page break is not displayed? displayed in the default slot?

Note that this may happen if the template for the first page (‘@page :first’) uses a letter that occurs in no other @page rule. Possibly also if a page template is bound to a “named page” [CSS3GCPM] and that named page is not allowed to repeat. (At the time of writing, this is only a proposal in the GCPM Module.)

Note that an element A that appears later in the document than an element B may thus be displayed on an earlier page than element B, because their respective slots are broken across pages in different ways.

Because of limitations of a device (e.g., limited memory), it may be that a UA has to print a page (force page breaks) even though some slots aren't filled yet.

This example shows how the first page may have a different layout from the other pages. The slot ‘a’ only occurs on the first page. If the content for that slot (in this case: all H1 elements) is too long, the remaining content of that slot will not be displayed. The slot ‘@’ occurs on normal pages and all its content can thus be displayed by adding additional pages.

@page :first { display: "a" "@" }
@page { display: "@" /* This is the default */ }
h1 {position: a}

Element-based templates in paged media may be broken across pages, subject to the page break properties. In addition to the break points listed in the Paged Media module [CSS3PAGE], a page break may occur between two rows in a template, if there is a possible break point at the same height or higher in all slots that span those two rows; and a page break may occur inside a row if there is a possible break point in all slots in that row.

Try to be more precise?

If ‘page-break-before’ or ‘page-break-after’ is ‘right’, ‘left’ or ‘always’ on an element inside a slot in an element-based template, the value is treated as ‘auto’ instead.

The ‘page’ property does not apply to elements inside a slot of an element-based template.

Any other forced page break (see section 5.5 of Paged Media [CSS3PAGE]) causes a new page to be created and all content in the document after this page break will be put in slots on the new page or on later pages: slots on any previous pages will not be further filled.

A slide presentation can be made with a template for each page (i.e., slide) and forced page break between the slides:

@page	{ display: "a" / 5em
               "@" / *
               "b" / auto }
h1	{ page-break-before: always;
      position: a }
p.note	{ position: b }

With a document similar to this: (fragment)

<h1>Slide 1 title</h1>
<ul>
 <li>Topic one
</ul>
<h1>Slide 2 title</h1>
<ul>
 <li>More topics
</ul>
<p class=note>Note the note

The document in the example above doesn't have an element that corresponds to a slide; a slide simply starts at an H1 and ends before the next H1. But if there is a DIV around each slide (as is the case in many slide formats in practice), the same effect can also be achieved without page-based templates, by using the ‘vh’ unit [CSS3VAL]:

div.slide {height: 100vh; display: "a"/5em "@" "b"/intrinsic;
    page-break-before: always}
h1 {position: a}
p.note {position: b}

With a document similar to this: (fragment)

<div class=slide>
 <h1>Slide 1 title</h1>
 <ul>
  <li>Topic one
 </ul>
</div>
<div class=slide>
 <h1>Slide 2 title</h1>
 <ul>
  <li>More topics
 </ul>
 <p class=note>Note the note
</div>

Both page-based and element-based templates can be used in the same document.

@page { display: "a@" }
:lang(fr} {position: a}
div.special {display: "abc" "abd"}

Here is a page as one might find in a newspaper. It combines a layout template with multicolumn layout.

5-column newspaper page with some blocks of text that span several columns

The front page of a newspaper, with the first parts of several stories that are continued on other pages and headings and images that span several columns.

@page :first {
  display: "A  A  A  A  A  A  A  A  A" / 5cm
           ".  .  .  .  .  .  .  .  ." / 0.25cm
           "B  .  C  C  C  C  C  C  C" / *
           "B  .  C  C  C  C  C  C  C" / *
           "B  .  C  C  C  C  C  C  C" / *
           "B  .  C  C  C  C  C  C  C" / *
           "B  .  C  C  C  C  C  C  C" / *
           "B  .  D  D  D  D  D  D  D" / *
           "B  .  D  D  D  D  D  D  D" / *
           "B  .  E  E  E  .  F  F  F" / *
           "B  .  E  E  E  .  F  F  F" / *
           "B  .  E  E  E  .  F  F  F" / *
            * 3em * 3em * 3em * 3em *
}
h1 {position: a; border-bottom: thick; margin-bottom: 1.5em}
#toc {position: b; margin-right: -1.5em; border-right: thin;
  padding-right: 1.5em}
#leader {position: c; columns: 4; column-gap: 3em}
#art1 {position: d; columns: 4; column-gap: 3em; border-top: thin}
#art2 {position: e; columns: 2; column-gap: 3em}
#art3 {position: f; columns: 2; column-gap: 3em}

If a slot on a page is full and the content continues on the next page, it may be useful to insert something like “continued on page X.” This is useful at any page break, but more important if there are multiple “flows” of content on each page. Maybe a page-break-content property? ‘page-break-content: "▶ continued on p. " targetcounter(???, page)’ or extend text-overflow from [CSS3TEXT]?

How do you set the ‘vertical-align’ property of a slot in a page? Does the ‘::slot()’ pseudo-element apply? ‘@page :first :slot(A) {vertical-align: bottom}’

10 Stacking order

An element with a computed value of a letter for its ‘position’ is a positioned element (see [CSS3POS]) and thus the ‘z-index’ property applies to it. The general rules for stacking contexts [ref in CSS3?] apply.

Note that an element can only have such a computed value if it has an ancestor that is a template element.

This example uses ‘z-index’ and negative margins to make the element in the middle slot partly overlap the other slots:

body { display: "a.b"
                ".c."
                "d.e";
       height: 240px;
       width: 240px }
::slot(a) { background: #0C0 }
::slot(b) { background: #C00 }
::slot(d) { background: #00C }
::slot(e) { background: #A0A }
#c { background: #FD0; height: 120px; position: c;
     margin: -20px; z-index: 1 }

Five colored rectangles

Rendering of the above example.

11 Floating elements inside templates

An element may be positioned inside a template (computed value of <letter> for its ‘position’ property) and be a floating element at the same time (computed value of its ‘float’ property is other than ‘none’). The following cases must be distinguished:

  • Page-based floats – In paged media (see [CSS3PAGE]), if the value of ‘float’ specifies that the element floats to the top or bottom of the page (in a horizontal writing mode) or the left or right of the page (in a vertical writing mode), the ‘position’ property doesn't apply.
  • Normal floats – In other cases, the element floats normally within its containing block, which in this case is its slot in the template (as defined above).

12 Definition of the ‘gr’ unit in a template element

The Grid Positioning Module [CSS3GRID] defines a ‘gr’ unit that is usable with certain properties that position or size boxes. A template element defines an implicit grid (in the terminology of that module) for use with the ‘gr’ unit. The vertical grid lines are formed by the left and right content edges of the template element and by the edges between the columns of the template. The horizontal grid lines are formed by the top and bottom content edges of the template element and by the edges between the rows of the template. The top content edge and the left content edge have the number 0.

In other words, a template with n columns and m rows defines n + 1 vertical grid lines numbered 0 to n and m + 1 horizontal grid lines numbered 0 to m.

For example, with the following style sheet

div {
  display: "abc"
           "def";
  position: relative}
p {
  position: f}
#p1 {
  position: absolute;
  top: 1gr;
  left: 2gr}

and this document fragment

<div>
 <p>Lorem ipsum dolor sit amet, consectetaur adipisicing elit, sed
 do eiusmod tempor incididunt ut labore et dolore magna aliqua.
 <p id=p1>Position me.
</div>

the “p1” element will be positioned with its top left corner against the top left corner of slot f. But note that it is not part of the content of slot f, it overlaps with it.

13 CR exit criteria

For this specification to be advanced to Proposed Recommendation, there must be at least two independent, interoperable implementations of each feature. Each feature may be implemented by a different set of products, there is no requirement that all features be implemented by a single product. For the purposes of this criterion, we define the following terms:

independent
each implementation must be developed by a different party and cannot share, reuse, or derive from code used by another qualifying implementation. Sections of code that have no bearing on the implementation of this specification are exempt from this requirement.
interoperable
passing the respective test case(s) in the official CSS test suite, or, if the implementation is not a Web browser, an equivalent test. Every relevant test in the test suite should have an equivalent test created if such a user agent (UA) is to be used to claim interoperability. In addition if such a UA is to be used to claim interoperability, then there must one or more additional UAs which can also pass those equivalent tests in the same way for the purpose of interoperability. The equivalent tests must be made publicly available for the purposes of peer review.
implementation
a user agent which:
  1. implements the specification.
  2. is available to the general public. The implementation may be a shipping product or other publicly available version (i.e., beta version, preview release, or “nightly build”). Non-shipping product releases must have implemented the feature(s) for a period of at least one month in order to demonstrate stability.
  3. is not experimental (i.e., a version specifically designed to pass the test suite and is not intended for normal usage going forward).

The specification will remain Candidate Recommendation for at least six months.

A test suite will be developed during the Candidate Recommendation phase of this specification.

14 History

(This section is not normative.)

The following types of use cases were considered for template-based layout.

  1. Standard Web pages.

  2. Grids and other table-like layouts. This includes grid layouts, frame layouts and table-like subdivision of a rectangular area.

  3. A layout structure with “flex”ing information. The flexing is represented by constraints that specify how the cells are to relate to one another: which cells are to be allowed to grow or shrink and how much. There may also be a priority ordering, which determines, based on the size of the allowed display window, which cells shrink, which grow and under which conditions.

  4. Layout structures with absolutely positioned (fixed-size) elements; for example a block of text into which several illustrations intrude at fixed positions within the block. This is like a float with respect to tightly wrapping the text around the intrusion, but the position of the intrusion is determined by the layout structure, not the content flowed into that structure.

    An example of this is a multicolumn layout with one or more “absolutely positioned floats” that intrude on the columns (see figure).

    An image that partially overlaps two columns makes the text wrap around it on both sides.

    An image (or a “pull quote”) is placed centered on the page and intrudes on two areas.

  5. Multiple, disconnected, fixed-size areas on a page that are chained together, each one receiving the content that doesn't fit in the previous slot. In combination with page breaks, this may give a layout as often seen in newspapers: the first few lines of each story on the first page, the rest of the story in other areas on subsequent pages. (It will probably need a way to conditionally insert“continued on page 7” or similar text.)

For comparing proposals for template-based layouts, the working group identified four important aspects of each proposal:

  1. the physical layout structures – the way of structuring the “cells” (slots) into which content is flowed. This includes a way to identify the various layout containers.

  2. the binding mechanism – the way to specify that a given element (and its descendants) are to be placed in a given layout cell.

  3. the property distribution mechanism – the way to put properties onto the layout structure and the cells within it.

  4. the flexing mechanism – the way to describe how the layout structure should adapt itself to the higher level container (window) in which it is placed. This includes statements about which cells should grow and when they should grow.

In this specification, these aspects are as follows:

  1. A character matrix is used to show the layout structure and the cells are named by the character used to show where they are positioned.

  2. The binding of content to cells is handled by the ‘position’ property which identifies a cell to which the content is bound.

  3. The shape, size and flexibility of the layout are specified with the character matrix. Some properties (background, border and vertical alignment) are attached to individual slots.

  4. There is limited “flexing” information. The choice is between fixed size, a fraction of the available size or the content's intrinsic size. (The latter is further subject to min/max sizes specified on that content.) It is not possible to say, e.g., that some column can only become wider if all other columns are at their maximum size.

Acknowledgments

The first ideas for describing a template in CSS date from 1996 and are described in Frame-based layout via Style Sheets by Bert Bos, Dave Raggett and Håkon Wium Lie. The idea was revived in 2005 on the request of W3C's Device Independence Working Group and benefited especially from discussions with Rhys Lewis and Rotan Hanrahan from that group.

This specification was further influenced by ideas about form layout by Dave Raggett [member-only link] and an early write-up of the features of XUL by Ian Hickson [member-only link].

Andy Clarke, Jina Bolton and Kevin Lawver provided use cases, examples and requirements. The analysis in the History section is a slightly shortened version of work by Steve Zilles.

César Acebal built the first prototype. Andrew Fedoniouk built the second. A third prototype was made by Alexis Deveria.

References

Normative references:

[CSS3BG]
Bert Bos; Elika J. Etemad; Brad Kemper. CSS Backgrounds and Borders Module Level 3. 15 October 2009. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2009/WD-css3-background-20091015
[CSS3BOX]
Bert Bos. CSS basic box model. 9 August 2007. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2007/WD-css3-box-20070809
[CSS3PAGE]
Melinda Grant; Håkon Wium Lie. CSS3 Module: Paged Media. 10 October 2006. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2006/WD-css3-page-20061010
[CSS3POS]
Bert Bos. CSS3 Positioning Module. (forthcoming). W3C Working Draft. (Work in progress.)
[CSS3SYN]
L. David Baron. CSS3 module: Syntax. 13 August 2003. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2003/WD-css3-syntax-20030813
[CSS3TBL]
Bert Bos; David Hyatt. CSS3 Tables Module. (forthcoming). W3C Working Draft. (Work in progress.)
[CSS3TEXT]
Paul Nelson; Elika J. Etemad. CSS Text Level 3. 6 March 2007. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2007/WD-css3-text-20070306
[CSS3TEXTLAYOUT]
Elika J. Etemad; Paul Nelson. CSS3 Text Layout Module. (forthcoming). W3C Working Draft. (Work in progress.)
[CSS3VAL]
Chris Lilley; Håkon Wium Lie. CSS3 Values and Units. 19 September 2006. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2006/WD-css3-values-20060919
[UNICODE]
The Unicode Consortium. The Unicode Standard. 2003. Defined by: The Unicode Standard, Version 4.0 (Boston, MA, Addison-Wesley, ISBN 0-321-18578-1), as updated from time to time by the publication of new versions URL: http://www.unicode.org/unicode/standard/versions/enumeratedversions.html

Other references:

[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 8 September 2009. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2009/CR-CSS2-20090908
[CSS3-FLEXBOX]
L. David Baron. Flexible Box Layout Module. 23 July 2009. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2009/WD-css3-flexbox-20090723
[CSS3GCPM]
Håkon Wium Lie. CSS3 module: Generated Content for Paged Media. 4 May 2007. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2007/WD-css3-gcpm-20070504
[CSS3GRID]
Alex Mogilevsky; Markus Mielke. CSS Grid Positioning Module Level 3. 5 September 2007. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2007/WD-css3-grid-20070905
[MEDIAQ]
Daniel Glazman; et al. Media Queries. 23 April 2009. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2009/CR-css3-mediaqueries-20090423
[SELECT]
Tantek Çelik; et al. Selectors Level 3. 10 March 2009. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2009/WD-css3-selectors-20090310

Index

  • ‘slot()’ pseudo-element., 7
  • <col-width>, 3
  • <length>, 1
  • <letter>, 6
  • <row-height>, 3
  • <string>, 1
  • anonymous block of a slot, 5
  • background, 1
  • block-flow, 1
  • box-shadow, 1
  • direction, 1
  • display, 1, 3
  • element-based template., 9
  • float, 1
  • height, 1
  • interactive, 1
  • intrinsic minimum width, 4
  • intrinsic preferred width, 4
  • layout algorithm, 4
  • non-interactive, 1
  • overflow, 1
  • page, 1
  • page area, 1
  • page-based template, 9
  • page-break-after, 1
  • page-break-before, 1
  • position, 6
  • slot, 3
  • template ancestor, 3
  • template element., 3
  • vertical-align, 1
  • width, 1
  • z-index, 1


CSS3 Transitions Module

CSS Transitions Module Level 3

W3C Working Draft 01 December 2009

This version:
http://www.w3.org/TR/2009/WD-css3-transitions-20091201
Latest version:
http://www.w3.org/TR/css3-transitions
Previous version:
http://www.w3.org/TR/2009/WD-css3-transitions-20090320
Editors:
Dean Jackson (Apple Inc)
David Hyatt (Apple Inc)
Chris Marrin (Apple Inc)
L. David Baron (Mozilla)

Copyright © 2009 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

CSS Transitions allows property changes in CSS values to occur smoothly over a specified duration.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css3-transitions” in the subject, preferably like this: “[css3-transitions] …summary of comment…”

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

The list of changes made to this specification is available.

Table of contents

  • 1. Introduction
  • 2. Transitions
    • 2.1. The ‘transition-property’ Property
    • 2.2. The ‘transition-duration’ Property
    • 2.3. The ‘transition-timing-function’ Property
    • 2.4. The ‘transition-delay’ Property
    • 2.5. The ‘transition’ Shorthand Property
  • 3. Starting of transitions
  • 4. Automatically reversing transitions
  • 5. Transition Events
  • 6. Animation of property types
  • 7. Animatable properties
    • 7.1. Properties from CSS
    • 7.2. Properties from SVG
  • 8. References
    • Normative references
    • Other references
  • Property index
  • Index

1. Introduction

This section is not normative.

This document introduces new CSS features to enable implicit transitions, which describe how CSS properties can be made to change smoothly from one value to another over a given duration.

2. Transitions

Normally when the value of a CSS property changes, the rendered result is instantly updated, with the affected elements immediately changing from the old property value to the new property value. This section describes a way to specify transitions using new CSS properties. These properties are used to animate smoothly from the old state to the new state over time.

For example, suppose that transitions of one second have been defined on the ‘left’ and ‘background-color’ properties. The following diagram illustrates the effect of updating those properties on an element, in this case moving it to the right and changing the background from red to blue. This assumes other transition parameters still have their default values.

Transitions of ‘left’ and ‘background-color’

Transitions are a presentational effect. The computed value of a property transitions over time from the old value to the new value. Therefore if a script queries the computed style of a property as it is transitioning, it will see an intermediate value that represents the current animated value of the property.

Only animatable CSS properties can be transitioned. See the table at the end of this document for a list of properties that are animatable.

The transition for a property is defined using a number of new properties. For example:

Example(s):

  div {
    transition-property: opacity;
    transition-duration: 2s;
  }
The above example defines a transition on the ‘opacity’ property that, when a new value is assigned to it, will cause a smooth change between the old value and the new value over a period of two seconds.

Each of the transition properties accepts a comma-separated list, allowing multiple transitions to be defined, each acting on a different property. In this case, the individual transitions take their parameters from the same index in all the lists. For example:

Example(s):

  div {
    transition-property: opacity, left;
    transition-duration: 2s, 4s;
  }
This will cause the ‘opacity’ property to transition over a period of two seconds and the left property to transition over a period of four seconds.

In the case where the list of values in transition properties do not have the same length, the list is repeated as a whole in order to provide necessary values.

Issue: Are the lists repeated to all be the length of the longest list, or are they repeated or truncated to match the length of the ‘transition-property’ list?

Example(s):

      div {
        transition-property: opacity, left, top, width;
        transition-duration: 2s, 1s;
      }
The above example defines a transition on the ‘opacity’ property of 2 seconds duration, a transition on the ‘left’ property of 1 second duration, a transition on the ‘top’ property of 2 seconds duration and a transition on the ‘width’ property of 1 second duration.

2.1. The ‘transition-property’ Property

The ‘transition-property’ property specifies the name of the CSS property to which the transition is applied.

We may ultimately want to support a keypath syntax for this property. A keypath syntax would enable different transitions to be specified for components of a property. For example the blur of a shadow could have a different transition than the color of a shadow.
Name: | transition-property
Value: | none | all | [ <IDENT> ] [ ‘,’ <IDENT> ]*
Initial: | all
Applies to: | all elements, :before and :after pseudo elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | Same as specified value.

A value of ‘none’ means that no property will transition. A value of ‘all’ means that every property that is able to undergo a transition will do so. Otherwise, a list of properties to be transitioned is given.

We need to generate a list of properties that can be transitioned.
Is "none" even a useful value if the initial value is "all"? The syntax is more elegant if transition-duration defaults to 0 and this property defaults to "all", but another option is to default this property to "none" and duration to something reasonable, e.g., 250ms. This would force an author to specify transition-property in the shorthand all the time though.

If one of the identifiers listed is not a recognized property name or is not an animatable property, the implementation must still start transitions on the animatable properties in the list using the duration, delay, and timing function at their respective indices in the lists for ‘transition-duration’, ‘transition-delay’, and ‘transition-timing-function’. In other words, unrecognized or non-animatable properties must be kept in the list to preserve the matching of indices.

Are ‘all’, ‘none’, ‘inherit’, and ‘initial’ allowed as items in a list of identifiers (of length greater than one)?

If one of the identifiers listed is a shorthand property, implementations must start transitions for any of its longhand sub-properties that are animatable, using the duration, delay, and timing function at the index corresponding to the shorthand.

If a property is specified multiple times in the value of ‘transition-property’ (either on its own or via a shorthand that contains it), then the transition that starts uses the duration, delay, and timing function at the index corresponding to the last occurrence of the property.

2.2. The ‘transition-duration’ Property

The ‘transition-duration’ property defines the length of time that a transition takes.

Name: | transition-duration
Value: | <time> [, <time>]*
Initial: | 0
Applies to: | all elements, :before and :after pseudo elements
Inherited: | no
Percentages: | N/A
Media: | interactive
Computed value: | Same as specified value.

This property specifies how long the transition from the old value to the new value should take. By default the value is ‘0’, meaning that the transition is immediate (i.e. there will be no animation). A negative value for transition-duration is treated as ‘0’.

2.3. The ‘transition-timing-function’ Property

The ‘transition-timing-function’ property describes how the intermediate values used during a transition will be calculated. It allows for a transition to change speed over its duration. These effects are commonly called easing functions. In either case, a mathematical function that provides a smooth curve is used.

The timing function is specified using a cubic bezier curve, which is defined by four control points, P0 through P3 (see Figure 1). P0 and P3 are always set to (0,0) and (1,1). The ‘transition-timing-function’ property is used to specify the values for points P1 and P2. These can be set to preset values using the keywords listed below, or can be set to specific values using the ‘cubic-bezier’ function. In the ‘cubic-bezier’ function, P1 and P2 are each specified by both an X and Y value.

The timing function is a smooth curve from point P0 = (0,0) to point P3 = (1,1). The length and orientation of the line segment P0-P1 determines the tangent and the curvature of the curve at P0 and the line segment P2-P3 does the same at P3.

Timing Function Control Points

The timing function takes as its input the current elapsed percentage of the transition duration and outputs a percentage that determines how close the transition is to its goal state.

Name: | transition-timing-function
Value: | ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier(<number>, <number>, <number>, <number>) [, ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier(<number>, <number>, <number>, <number>)]*
Initial: | ease
Applies to: | all elements, :before and :after pseudo elements
Inherited: | no
Percentages: | N/A
Media: | interactive
Computed value: | Same as specified value.

POWERED BY HeroNote

The timing functions have the following definitions.

ease
The ease function is equivalent to cubic-bezier(0.25, 0.1, 0.25, 1.0).
linear
The linear function is equivalent to cubic-bezier(0.0, 0.0, 1.0, 1.0).
ease-in
The ease-in function is equivalent to cubic-bezier(0.42, 0, 1.0, 1.0).
ease-out
The ease-out function is equivalent to cubic-bezier(0, 0, 0.58, 1.0).
ease-in-out
The ease-in-out function is equivalent to cubic-bezier(0.42, 0, 0.58, 1.0)
cubic-bezier
Specifies a cubic-bezier curve. The four values specify points P1 and P2 of the curve as (x1, y1, x2, y2). All values must be in the range [0, 1] or the definition is invalid.

2.4. The ‘transition-delay’ Property

The ‘transition-delay’ property defines when the transition will start. It allows a transition to begin execution some some period of time from when it is applied. A ‘transition-delay’ value of ‘0’ means the transition will execute as soon as the property is changed. Otherwise, the value specifies an offset from the moment the property is changed, and the transition will delay execution by that offset.

If the value for ‘transition-delay’ is a negative time offset then the transition will execute the moment the property is changed, but will appear to have begun execution at the specified offset. That is, the transition will appear to begin part-way through its play cycle. In the case where a transition has implied starting values and a negative ‘transition-delay’, the starting values are taken from the moment the property is changed.

Name: | transition-delay
Value: | <time> [, <time>]*
Initial: | 0
Applies to: | all elements, :before and :after pseudo elements
Inherited: | no
Percentages: | N/A
Media: | interactive
Computed value: | Same as specified value.

2.5. The ‘transition’ Shorthand Property

The ‘transition’ shorthand property combines the four properties described above into a single property.

Note that order is important in this property. The first value that can be parsed as a time is assigned to the transition-duration. The second value that can be parsed as a time is assigned to transition-delay.

An alternative proposal is to accept the font shorthand approach of using a "/" character between the values of the same type. eg. 2s/4s would mean a duration of 2 seconds and a delay of 4 seconds.

Name: | transition
Value: | [<‘transition-property’> || <‘transition-duration’> || <‘transition-timing-function’> || <‘transition-delay’> [, [<‘transition-property’> || <‘transition-duration’> || <‘transition-timing-function’> || <‘transition-delay’>]]*
Initial: | see individual properties
Applies to: | all elements, :before and :after pseudo elements
Inherited: | no
Percentages: | N/A
Media: | interactive
Computed value: | Same as specified value.

3. Starting of transitions

When the value of an animatable property changes, implementations must decide what transitions to start based on the values of the ‘transition-property’, ‘transition-duration’, ‘transition-timing-function’, and ‘transition-delay’ properties at the time of the change. Since this specification does not define what property changes are considered simultaneous, authors should be aware that changing any of the transition properties a small amount of time after making a change that might transition can result in behavior that varies between implementations, since the changes might be considered simultaneous in some implementations but not others.

Once the transition of a property has started, it must continue running based on the original timing function, duration, and delay, even if the ‘transition-timing-function’, ‘transition-duration’, or ‘transition-delay’ property changes before the transition is complete. However, if the ‘transition-property’ property changes such that the transition would not have started, the transition must stop (and the property must immediately change to its final value).

Implementations must not start a transition when the computed value of a property changes as a result of declarative animation (as opposed to scripted animation).

Implementations also must not start a transition when the computed value changes because it is inherited (directly or indirectly) from another element that is transitioning the same property.

4. Automatically reversing transitions

A common type of transition effect is when a running transition is interrupted and the property is reset to its original value. An example is a hover effect on an element, where the pointer enters and exits the element before the effect has completed. If the outgoing and incoming transitions are executed using their specified durations and timing functions, the resulting effect can be distractingly asymmetric. Instead, the expected behavior is that the new transition should be the reverse of what has already executed.

If a running transition with duration T, executing so far for duration TE, from state A, to state B, is interrupted by a property change that would start a new transition back to state A, and all the transition attributes are the same (duration, delay and timing function), then the new transition must reverse the effect. The new transition must:

  1. Use the B and A states as its "from" and "to" states respectively. It does not use the current value as its from state, due to the rules below.
  2. Execute with the same duration T, but starting as if the transition had already begun, without any transition delay, at the moment which would cause the new transition to finish in TE from the moment of interruption. In other words, the new transition will execute as if it started T-TE in the past.
  3. Use a timing function that is the portion of the curve traversed up to the moment of interruption, followed in the opposite direction (towards the starting point). This will make the transition appear as if it is playing backwards.
  4. Ignore any transition delay.

For example, suppose there is a transition with a duration of two seconds. If this transition is interrupted after 0.5 seconds and the property value assigned to the original value, then the new transition effect will be the reverse of the original, as if it had begun 1.5 seconds in the past.

Note that by using the defined from and to states for the reversing transition, it is also possible that it may reverse again, if interrupted; for example, if the transition reversing to state A was again interrupted by a property change to state B.

5. Transition Events

The completion of a CSS Transition generates a corresponding DOM Event. An event is fired for each property that undergoes a transition. This allows a content developer to perform actions that synchronize with the completion of a transition.

Each event provides the name of the property the transition is associated with as well as the duration of the transition.

Interface TransitionEvent

The TransitionEvent interface provides specific contextual information associated with transitions.

IDL Definition
  interface TransitionEvent : Event {
    readonly attribute DOMString          propertyName;
    readonly attribute float              elapsedTime;
    void               initTransitionEvent(in DOMString typeArg,
                                          in boolean canBubbleArg,
                                          in boolean cancelableArg,
                                          in DOMString propertyNameArg,
                                          in float elapsedTimeArg);
  };
Attributes
propertyName of type DOMString, readonly
The name of the CSS property associated with the transition.
elapsedTime of type float, readonly
The amount of time the transition has been running, in seconds, when this event fired. Note that this value is not affected by the value of transition-delay.
Methods
initTransitionEvent
The initTransitionEvent method is used to initialize the value of a TransitionEvent created through the DocumentEvent interface. This method may only be called before the TransitionEvent has been dispatched via the dispatchEvent method, though it may be called multiple times during that phase if necessary. If called multiple times, the final invocation takes precedence.
Parameters
typeArg of type DOMString
Specifies the event type.
canBubbleArg of type boolean
Specifies whether or not the event can bubble.
cancelableArg of type boolean
Specifies whether or not the event's default action can be prevented. Since a TransitionEvent is purely for notification, there is no default action.
propertyNameArg of type DOMString
Specifies the name of the property associated with the Event
elapsedTimeArg of type float
Specifies the amount of time, in seconds, the transition has been running at the time of initialization.
No Return Value
No Exceptions

There is one type of transition event available.

transitionend
The ‘transitionend’ event occurs at the completion of the transition. In the case where a transition is removed before completion, such as if the transition-property is removed, then the event will not fire.
  • Bubbles: Yes
  • Cancelable: Yes
  • Context Info: propertyName, elapsedTime

6. Animation of property types

The following describes how each property type undergoes transition or animation.

  • color: interpolated via red, green, blue and alpha components (treating each as a number, see below).
    Issue: Are the colors interpolated in premultiplied space or non-premultiplied space?
  • length: interpolated as real numbers.
  • percentage: interpolated as real numbers.
  • integer: interpolated via discrete steps (whole numbers). The interpolation happens in real number space and is converted to an integer using floor().
  • number: interpolated as real (floating point) numbers.
  • transform list: see CSS Transforms specification [CSS3-2D-TRANSFORMS].
  • rectangle: interpolated via the x, y, width and height components (treating each as a number).
  • visibility: interpolated via a discrete step. The interpolation happens in real number space between 0 and 1, where 1 is "visible" and all other values are "hidden".
  • shadow: interpolated via the color, x, y and blur components (treating them as color and numbers where appropriate). In the case where there are lists of shadows, the shorter list is padded at the end with shadows whose color is transparent and all lengths (x, y, blur) are 0.
  • gradient: interpolated via the positions and colors of each stop. They must have the same type (radial or linear) and same number of stops in order to be animated.
  • paint server (SVG): interpolation is only supported between: gradient to gradient and color to color. They then work as above.
  • space-separated list of above: If the lists have the same number of items, each item in the list is interpolated using the rules above. Otherwise, no interpolation (unless stated otherwise above).
  • a shorthand property: If all the parts of a shorthand can be animated, then interpolation is performed as if each property was individually specified.

7. Animatable properties

7.1. Properties from CSS

Property Name | Type
background-color | color
background-image | only gradients
background-position | percentage, length
border-bottom-color | color
border-bottom-width | length
border-color | color
border-left-color | color
border-left-width | length
border-right-color | color
border-right-width | length
border-spacing | length
border-top-color | color
border-top-width | length
border-width | length
bottom | length, percentage
color | color
crop | rectangle
font-size | length, percentage
font-weight | number
grid-* | various
height | length, percentage
left | length, percentage
letter-spacing | length
line-height | number, length, percentage
margin-bottom | length
margin-left | length
margin-right | length
margin-top | length
max-height | length, percentage
max-width | length, percentage
min-height | length, percentage
min-width | length, percentage
opacity | number
outline-color | color
outline-offset | integer
outline-width | length
padding-bottom | length
padding-left | length
padding-right | length
padding-top | length
right | length, percentage
text-indent | length, percentage
text-shadow | shadow
top | length, percentage
vertical-align | keywords, length, percentage
visibility | visibility
width | length, percentage
word-spacing | length, percentage
z-index | integer
zoom | number

7.2. Properties from SVG

All properties defined as animatable in the SVG specification, provided they are one of the property types listed above.

8. References

Normative references

[CSS3-2D-TRANSFORMS]
Dean Jackson; David Hyatt; Chris Marrin. CSS 2D Transforms Module Level 3. 20 March 2009. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2009/WD-css3-2d-transforms-20090320

Other references

Property index

Property | Values | Initial | Applies to | Inh. | Percentages | Media
transition | [<‘transition-property’> || <‘transition-duration’> || <‘transition-timing-function’> || <‘transition-delay’> [, [<‘transition-property’> || <‘transition-duration’> || <‘transition-timing-function’> || <‘transition-delay’>]]* | see individual properties | all elements, :before and :after pseudo elements | no | N/A | interactive
transition-delay | <time> [, <time>]* | 0 | all elements, :before and :after pseudo elements | no | N/A | interactive
transition-duration | <time> [, <time>]* | 0 | all elements, :before and :after pseudo elements | no | N/A | interactive
transition-property | none | all | [ <IDENT> ] [ ‘,’ <IDENT> ]* | all | all elements, :before and :after pseudo elements | no | N/A | visual
transition-timing-function | ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier(<number>, <number>, <number>, <number>) [, ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier(<number>, <number>, <number>, <number>)]* | ease | all elements, :before and :after pseudo elements | no | N/A | interactive

Index

  • transition, 2.5.
  • transition-delay, 2.4.
  • transition-duration, 2.2.
  • transition-property, 2.1.
  • transition-timing-function, 2.3.


CSS3 Values and Units

W3C Working Draft 19 September 2006

This version:
http://www.w3.org/TR/2006/WD-css3-values-20060919
Latest version:
http://www.w3.org/TR/css3-values
Previous version:
http://www.w3.org/TR/2005/WD-css3-values-20050726
Editors:
Håkon Wium Lie, Opera Software <howcome@opera.com>
Chris Lilley, W3C <chris@w3.org>

Copyright © 2006 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

This CSS3 module describes the various values and units that CSS properties accept. Also, it describes how values are computed from "specified" (which is what the cascading process yields) through "computed" and "used" into "actual" values. The main purpose of this module is to define common values and units in one specification which can be referred to by other modules. As such, it does not make sense to claim conformance with this module alone.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text "css3-values" in the subject, preferably like this: "[css3-values] .summary of comment."

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

All features described in this specification that also exist in CSS 2.1 [CSS21] are intended to be backwards compatible. In case of conflict between this draft and CSS 2.1 [CSS21], CSS 2.1 probably represents the intention of the CSS WG better than this draft (other than on values and units that are new to CSS3).

This is a draft of a module of CSS level 3. It will probably be bundled with some other modules before it becomes a W3C Recommendation.

Table of contents

  • 1. Dependencies on other modules
  • 2. Introduction
  • 3. Values
    • 3.1. Keywords
    • 3.2. Numbers
    • 3.3. Non-negative numbers
    • 3.4. Numbers with unit identifiers
      • 3.4.1. Lengths
      • 3.4.2. Relative length units
      • 3.4.3. Absolute length units
      • 3.4.4. Percentages
      • 3.4.5. Angles
    • 3.5. Non-negative numbers with unit identifiers
      • 3.5.1. Times
      • 3.5.2. Frequencies
    • 3.6. Strings
    • 3.7. Functional notation
      • 3.7.1. The 'attr' function
      • 3.7.2. The 'url' function
      • 3.7.3. The 'counter' function
      • 3.7.4. The 'calc' function
    • 3.8. Special cases
      • 3.8.1. Font families
      • 3.8.2. Colors
  • 4. Specified, computed, used, and actual values
    • 4.1. Cascaded values
    • 4.2. Specified values
    • 4.3. Computed values
    • 4.4. Used values
    • 4.5. Actual values
  • Acknowledgments
  • References
    • Normative references
    • Other references
  • Index

1. Dependencies on other modules

This CSS3 module depends on the following other CSS3 modules:

  • Cascading and Inheritance [CSS3CASCADE], which describes how to find the resulting value from several competing values. Also, it describes how to replace the "inherit" keyword with the inherited value.
  • Syntax [CSS3SYN], which describes the syntax of values at the lexical level.
  • Text [CSS3TEXT], which describes how to establish grids referred to by the 'gd' unit.
  • Color [CSS3COLOR], which defines additional values used for some properties that control color of text, borders, etc
  • Fonts [CSS3FONT], which describes additional values used for font-related properties

2. Introduction

There are eight main types of values in CSS:

  1. keywords (e.g. "pitch-range: inherit")
  2. numbers (e.g. "orphans: 3")
  3. non-negative numbers (e.g. "orphans: 3")
  4. numbers with unit identifiers (e.g. "border-left: -1.2em")
  5. non-negative numbers with unit identifiers (e.g. "border-width: 0.2em")
  6. strings (e.g. "content: 'Figure: '")
  7. functional notations (e.g. "background: url(http://www.example.org/image)")
  8. special cases (e.g. "color: #F00" and "font-family: Helvetica, sans-serif")

Should the special cases also be described in this draft?

Most properties accept values from several of the above types. Some properties accept space- or comma-separated lists of values. Comma-separated lists have optional whitespace before and after the comma.

Each CSS property has a formal definition of what types of values it accepts which can be found in the description of the property. For special case types not described in this module, the individual property descriptions should be consulted.

3. Values

3.1. Keywords

In the formal definition of property values, keywords appear literally.

For example, here is the value definition for the 'border-collapse' property:

Value: collapse | separate

And here is an example of its use:

table { border-collapse: separate }

All CSS3 properties accept the keyword values 'inherit' and 'initial'. Keywords must not be quoted.

Would it be useful to have a 'default' value, defined to be equivalent to 'inherit' for properties that are inherited by default and equivalent to 'initial' for properties that are not inherited by default? This might be easier for authors to use than 'initial' and 'inherit' since it wouldn't require thinking about whether a property is inherited by default or not (which isn't obvious for some properties, such as text-decoration and visibility).

3.2. Numbers

Number values can either be integer or real numbers. Integer values are denoted by <integer> and real number values are denoted by <number>. Integers and real numbers are specified in decimal notation only. An <integer> consists of one or more digits "0" to "9". A <number> can either be an <integer>, or it can be zero or more digits followed by a dot (.) followed by one or more digits. Both integers and real numbers may be preceded by a "-" or "+" to indicate the sign, and the sign character is considered part of the <number> value.

Note that many properties that allow an integer or real number as a value actually restrict the value to some range. If the restriction is to a non-negative value, then a non-negative number type is used.

3.3. Non-negative numbers

Non-negative number values can either be integer or real numbers. Integer values are denoted by <non-negative integer> and real number values are denoted by <non-negative number>. Integers and real numbers are specified in decimal notation only. A <non-negative-integer> consists of one or more digits "0" to "9". A <non-negative-number> can either be an <integer>, or it can be zero or more digits followed by a dot (.) followed by one or more digits. Both non-negative integers and non-negative real numbers may be preceded by a "+" to indicate the sign, but this is not required and conveys no useful information.

3.4. Numbers with unit identifiers

3.4.1. Lengths

Lengths refer to horizontal or vertical measurements.

The format of a length value (denoted by <length>) is a <number> immediately followed by a unit identifier (e.g., 'px', 'gd'). After the '0' length, the unit identifier is optional.

Some properties allow negative length values, but this may complicate the formatting and there may be implementation-specific limits. If a negative length value is allowed but cannot be supported, it should be converted to the nearest value that can be supported.

3.4.2. Relative length units

There are two types of length units: relative and absolute. Relative length units specify a length relative to another length property. Style sheets that use relative units will more easily scale from one medium to another (e.g., from a computer display to a laser printer).

Relative units are:

unit | relative to
em | the font size of the element (or, to the parent element's font size if set on the 'font-size' property)
ex | the x-height of the element's font
px | viewing device
gd | the grid defined by 'layout-grid' described in the CSS3 Text module [CSS3TEXT]
rem | the font size of the root element
vw | the viewport's width
vh | the viewport's height
vm | the viewport's height or width, whichever is smaller of the two
ch | The width of the "0" (ZERO, U+0030) glyph found in the font for the font size used to render. If the "0" glyph is not found in the font, the average character width may be used. How is the "average character width" found?

The 'em' unit is equal to the computed value of the 'font-size' property of the element on which it is used. The exception is when 'em' occurs in the value of the 'font-size' property itself, in which case it refers to the font size of the parent element. On the root element, It may be used for vertical or horizontal measurement. (This unit is also sometimes called the quad-width in typographic texts.)

The rule:

h1 { line-height: 1.2em }

means that the line height of h1 elements will be 20% greater than the font size of the elements. On the other hand:

h1 { font-size: 1.2em }

means that the font size of h1 elements will be 20% greater than the font size inherited by h1 elements.

h1 { margin: 0.5em }      /* em */
h1 { margin: 1ex }        /* ex */
p  { font-size: 12px }    /* px */

The 'ex' unit is defined by the font's x-height. The x-height is so called because it is often equal to the height of the lowercase "x". However, an 'ex' is defined even for fonts that don't contain an "x". Should we say that ex is 0.5em if no better value exists?

When specified on the 'font-size' property of the root element, 'em' and 'ex' units refer to the property's initial value.

The pixel unit, 'px' is relative to the resolution of the viewing device. For example, the viewing device can be a computer display or a printer. Normally, the pixel unit refers to physical pixels of the viewing device. However, if the pixel density of the output device is very different from that of a typical computer display, the user agent should rescale pixel values. It is recommended that the reference pixel be the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm's length. For a nominal arm's length of 28 inches, the visual angle is therefore about 0.0213 degrees.

For reading at arm's length, 1px thus corresponds to about 0.26mm (1/96 inch). When printed on a laser printer, meant for reading at a little less than arm's length (55 cm, 21 inches), 1px is about 0.21mm. On a 300 dots-per-inch (dpi) printer, that may be rounded up to 3 dots (0.25 mm); on a 600 dpi printer, it can be rounded to 5 dots.

The two images below illustrate the effect of viewing distance on the size of a pixel and the effect of a device's resolution. In the first image, a reading distance of 71cm (28 inch) results in a px of 0.26mm, while a reading distance of 3.5m (12 feet) requires a px of 1.3mm.

Showing that pixels must become larger if the viewing distance increases

In the second image, an area of 1px by 1px is covered by a single dot in a low-resolution device (a computer screen), while the same area is covered by 16 dots in a higher resolution device (such as a 400 dpi laser printer).

Showing that more device pixels (dots) are needed to cover a 1px by 1px area on a high-resolution device than on a low-res one

Grid units, 'gd', are frequently used in East Asian typography, especially for margins. The existence of a grid in an element makes it possible to express various measurements in terms of grid units.

Example(s):

p { layout-grid: strict both 20pt 15pt; margin: 1gd 3gd 1gd 2gd }

The 'layout-grid' property, described in the CSS3 Text module [CSS3TEXT], establishes the grid. In the example above, p elements acquire a 15pt top margin, a 60pt right margin, a 15pt bottom margin and a 40pt left margin.

If no grid is specified on the element, the 'gd' unit is treated as the 'em' unit.

The 'rem' unit ('root em') is relative to the computed value of the 'font-size' value of the root element. The exception is when 'rem' occurs in the value of the 'font-size' property of the root element itself, in which case it is relative to the 'medium' font-size. It may be used for vertical or horizontal measurement.

The 'vw' unit is relative to the viewport's width. The viewport's width is equal to 100 'vw' units.

Example:

h1 { font-size: 8vw }

If the width of the viewport is 200mm, the font size of h1 elements will be 16mm ((8×200)/100). When the width of the viewport is changed (for example, when the browser window is enlarged), lengths specifed in the 'vh' unit is scaled propertionally.

The 'vh' unit is relative to the viewport's height. The viewport's width is equal to 100 'vh' units. When the height of the viewport is changed (for example, when the browser window is enlarged), lengths specifed in the 'vh' unit are scaled proportionally.

The 'vm' unit is relative to the viewport's height or width, whichever of the two is smaller. The minimum of the viewport's width/height is equivalent to 100 'vm' units. When the height or width of the viewport is changed, lengths specified in the 'vm' unit are scaled proportionally.

3.4.3. Absolute length units

Absolute length units are useful when the physical properties of the output medium are known. The absolute units are:

unit | definition
in | inches; 1 inch is equal to 2.54 centimeters.
cm | centimeters
mm | millimeters
pt | points; 1pt is equal to 1/72 inch.
pc | picas; 1 pica is equal to 12 points.

Examples:

h1 { margin: 0.5in }      /* inches  */
h2 { line-height: 3cm }   /* centimeters */
h3 { word-spacing: 4mm }  /* millimeters */
h4 { font-size: 12pt }    /* points */
h4 { font-size: 1pc }     /* picas */

In cases where the specified length cannot be supported, user agents must approximate it in the actual value.

3.4.4. Percentages

The format of a percentage value (denoted by <percentage> in this specification) is a <number> immediately followed by '%'.

Percentage values are always relative to another value, for example a length. Each property that allows percentages also defines the value to which the percentage refers. The value may be that of another property for the same element, a property for an ancestor element, or a value of the formatting context (e.g., the width of a containing block). When a percentage value is set for a property of the root element and the percentage is defined as referring to the inherited value of some property, the resultant value is the percentage times the initial value of that property.

Example(s):

Since child elements (generally) inherit the computed values of their parent, in the following example, the children of the P element will inherit a value of 12pt for 'line-height', not the percentage value (120%):

p { font-size: 10pt }
p { line-height: 120% }  /* 120% of 'font-size' */

Do we need a "non-negative percentage", e.g. for "font-size"?

3.4.5. Angles

Angle values (denoted by <angle> in the text) are used with aural cascading style sheets.

Their format is a <number> immediately followed by an angle unit identifier.

Angle unit identifiers are:

  • deg: degrees
  • grad: grads
  • rad: radians
  • turn: turns

Angle values should be normalized to the range 0-360deg by the user agent. For example, -10deg and 350deg are equivalent.

For example, a right angle is '90deg' or '100grad' or '1.570796326794897rad'.

3.5. Non-negative numbers with unit identifiers

3.5.1. Times

Time values (denoted by <time> in the text) are used with aural cascading style sheets.

Their format is a <number> immediately followed by a time unit identifier.

Time unit identifiers are:

  • ms: milliseconds
  • s: seconds

3.5.2. Frequencies

Frequency values (denoted by <frequency> in the text) are used with aural cascading style sheets.

Their format is a <number> immediately followed by a frequency unit identifier.

Frequency unit identifiers are:

POWERED BY HeroNote
  • Hz: Hertz
  • kHz: kilohertz

For example, 200Hz (or 200hz) is a bass sound, and 6kHz (or 6khz) is a treble sound.

3.6. Strings

Strings can either be written with double quotes or with single quotes. Double quotes cannot occur inside double quotes, unless escaped (as '\"' or as '\22'). Analogously for single quotes ("\'" or "\27").

Example(s):

"this is a 'string'"
"this is a \"string\""
'this is a "string"'
'this is a \'string\''

A string cannot directly contain a newline. To include a newline in a string, use the escape "\A" (hexadecimal A is the line feed character in Unicode (U+000A), but represents the generic notion of "newline" in CSS). See the 'content' property for an example.

It is possible to break strings over several lines, for esthetic or other reasons, but in such a case the newline itself has to be escaped with a backslash (\). The newline is subsequently removed from the string. For instance, the following two selectors are exactly the same:

Example(s):

a[title="a not s\
o very long title"] {/*...*/}
a[title="a not so very long title"] {/*...*/}

3.7. Functional notation

The functional notation is used to denote colors, attributes and URIs in CSS3. The syntax of the functional notation is: the name of the functions (e.g. 'rgb') followed by a left parenthesis followed by optional whitespace followed by the argument(s) to the functions followed by optional whitespace followed by a right parenthesis. If a function takes more than one argument, the arguments are separated by a comma (',') with optional whitespace before and after the comma.

3.7.1. The 'attr' function

In CSS2.1 [CSS21], the 'attr()' expression always returns a string. In CSS3, the 'attr()' expression can return many different types. The new syntax for the attr() expression is:

'attr(' ident [ ',' <type> [ ',' <value> ]? ]? ')'

The first argument represents the attribute name. The value of the attribute with that name on the element whose computed values are being computed is used as the value of the expression, according to the rules given below.

The first argument accepts an optional namespace prefix to identify the namespace of the attribute. The namespace prefix and the attribute name is separated by '|', with no whitespace before or after the separator [CSS3NAMESPACE].

The second argument (which is optional but must be present if the third argument is present) is a <type> and tells the UA how to interpret the attribute value. It may be one of the values from the list below.

The third argument (which is optional) is a CSS value which must be valid where the attr() expression is placed. If it is not valid, then the whole attr() expression is invalid.

If the attribute named by the first argument is missing, cannot be parsed, or is invalid for the property, then the value returned by attr() will be the third argument, or, if the third argument is absent, will be the value given as the default for the relevant type in the list below.

string
The attribute value will be interpreted as the contents of a CSS string. The default is the empty string.
color
The attribute value will be interpreted as a CSS <color> value. The default is UA dependent but must be the same as the initial value of the 'color' property.
url
The attribute value will be interpreted as the URI part of a 'url()' expression. The default is a UA-dependent URI defined to point to a non-existent document with a generic error condition. (i.e. it shouldn't be an FTP URI that causes a DNS error, or an HTTP URI that results in a 404, it should be a non-descript error condition.)
integer
The attribute value will be interpreted as a CSS integer. The default is 0. The default should also be used if the property in question only accepts integers within a certain range and the attribute is out of range.
number
The attribute value will be interpreted as a CSS number. The default is 0.0. The default should also be used if the property in question only accepts numbers within a certain range and the attribute is out of range.
length, angle, time, frequency
The attribute value will be interpreted as a CSS length, angle, time or frequency (respectively), and the unit identifier (if any) will appear in the attribute value. The default is 0. The default should also be used if the property in question only accepts values within a certain range (e.g. positive lengths or angles from 0 to 90deg) and the attribute is out of range (e.g. a negative length or 180deg).
em, ex, px, gd, rem, vw, vh, vm, mm, cm, in, pt, pc, deg, grad, rad, ms, s, Hz, kHz, %
The attribute value will be interpreted as a float, with the given type suffixed as a unit. The default is 0 in the relevant units.

Should there also be a "keyword" type to, e.g., support 'float: attr(align)'

If the <type> is missing, 'string' is implied.

Ideally, it shouldn't be necessary to specify the type if it is obvious. For example, this should be valid: "background-image: attr(href);". This could be described as: If the property only accepts one type of value (aside from 'inherit' and 'initial'), that type is implied.

The attr() form is only valid if the type given (or implied, if it is missing) is valid for the property. For example, all of the following are invalid and would cause a parse-time error (and thus cause the relevant declaration, in this case all of them, to be ignored):

Illegal Examples:

      content: attr(title, color); /* 'content' doesn't accept colors */

      content: attr(end-of-quote, string, inherit) close-quote; /* the
      'inherit' value is not allowed there, since the result would be
      'inherit close-quote', which is invalid. */

      margin: attr(vertical, length) attr(horizontal, deg); /* deg
      units are not valid at that point */

      color: attr(color); /* 'color' doesn't accept strings */

The attr() expression cannot return everything, for example it cannot do counters, named strings, quotes, or values such as 'auto', 'nowrap', or 'baseline'. This is intentional, as the intent of the 'attr()' expression is not to make it possible to describe a presentational language's formatting using CSS, but to enable CSS to take semantic data into account.

Note that the default value need not be of the type given. For instance, if the type required of the attribute by the author is 'px', the default could still be '5em'.

Examples:

      <stock>
        <wood length="12"/>
        <wood length="5"/>
        <metal length="19"/>
        <wood length="4"/>
      </stock>

      stock::before {
        display: block;
        content: "To scale, the lengths of materials in stock are:";
      }
      stock > * {
        display: block;
        width: attr(length, em); /* default 0 */
        height: 1em;
        border: solid thin;
        margin: 0.5em;
      }
      wood {
        background: orange url(wood.png);
      }
      metal {
        background: silver url(metal.png);
      }

      /* this also uses a possible extension to the 'content' property
      to handle replaced content and alternatives to unavailable,
      corrupted or unsupported content */
      img {
         content: replaced attr(src, url), attr(alt, string, none);
         height: attr(height, px, auto);
         width: attr(width, px, auto);
      }

The attr() expression cannot currently fall back onto another attribute. Future versions of CSS may extend attr() in this direction.

Should 'attr()' be allowed on any property, in any source language? For example, do we expect UAs to honor this rule for HTML documents?: P[COLOR] { color: attr(COLOR, color) }.

3.7.2. The 'url' function

URLs (Uniform Resource Locators, see [RFC1738] and [RFC1808]) provide the address of a resource on the Web. An alternative and more general term is URIs (Uniform Resource Identifiers, see [!URI]). This specification uses the term URI.

For historical reasons, the name of the URI function is "url". The URI function takes one URI as the argument. The URI may be quoted with single quote (') or double quote (") characters. If quoted, the two quote characters must be the same.

Example(s):

body { background: url("http://www.example.com/pinkish.gif") }

Example(s):

An example without quotes:

li { list-style: url(http://www.example.com/redball.png) disc }

Parentheses, commas, whitespace characters, single quotes (') and double quotes (") appearing in a URI must be escaped with a backslash: '\(', '\)', '\,'.

Depending on the type of URI, it might also be possible to write the above characters as URI-escapes (where "(" = %28, ")" = %29, etc.) as described in [!URI].

In order to create modular style sheets that are not dependent on the absolute location of a resource, authors may use relative URIs. Relative URIs (as defined in [RFC1808]) are resolved to full URIs using a base URI. RFC 1808, section 3, defines the normative algorithm for this process. For CSS style sheets, the base URI is that of the style sheet, not that of the source document.

Example(s):

For example, suppose the following rule:

body { background: url("yellow") }

is located in a style sheet designated by the URI:

http://www.example.org/style/basic.css

The background of the source document's BODY will be tiled with whatever image is described by the resource designated by the URI

http://www.example.org/style/yellow

User agents may vary in how they handle URIs that designate unavailable or inapplicable resources.

3.7.3. The 'counter' function

Counters are denoted by identifiers (see the 'counter-increment' and 'counter-reset' properties). To refer to the value of a counter, the notation 'counter(<identifier>)' or 'counter(<identifier>, <list-style-type>)' is used. The default style is 'decimal'.

To refer to a sequence of nested counters of the same name, the notation is 'counters(<identifier>, <string>)' or 'counters(<identifier>, <string>, <list-style-type>)'. See "Nested counters and scope" [add ref] in the chapter on generated content [add ref].

In CSS2.1, the values of counters can only be referred to from the 'content' property. Note that 'none' is a possible <list-style-type>: 'counter(x, none)' yields an empty string.

Example(s):

Here is a style sheet that numbers paragraphs (P) for each chapter (H1). The paragraphs are numbered with roman numerals, followed by a period and a space:

p { counter-increment: par-num }
h1 { counter-reset: par-num }
p:before { content: counter(par-num, upper-roman) ". " }

3.7.4. The 'calc' function

The calc(<expression>) function can be used wherever length values are allowed. The expression within the parethesis is computed at the same time as 'em' lengths are computed, with the syntax given below.

section {
  float: left;
  margin: 1em; border: solid 1px;
  width: calc(100%/3 - 2*1em - 2*1px);
}

p {
  margin: calc(1rem - 2px) calc(1rem - 1px);
  border: solid transparent; border-width: 2px 1px;
}
p:hover { border-color: yellow; }

The simple expression language of the 'calc()' function supports five arithmetic operators (+ and - have lowest precedence, *, /, and 'mod' have highest precedence) and parentheses. At a later date new operators such as min/max, conditionals, etc, and maybe new constants may be added.

The expression language is defined by 'length-expression' below:

  <length> := calc( <length-expression> ) | <atomic-length>

  <length-expression> := <length-additive-expression>

  <length-additive-expression> :=
     <length-multiplicative-expression> |
     <length-additive-expression> '+' <length-multiplicative-expression> |
     <length-additive-expression> '-' <length-multiplicative-expression>

  <length-multiplicative-expression>
     <length-term> |
     <length-multiplicative-expression> '*' <number-term> |
     <number-multiplicative-expression> '*' <length-term> |
     <length-multiplicative-expression> '/' <number-term> |
     <length-multiplicative-expression> 'mod' <number-term>

  <length-term> := '(' <length-expression> ')' | <atomic-length>

  <number-additive-expression> :=
     <number-multiplicative-expression> |
     <number-additive-expression> '+' <number-multiplicative-expression> |
     <number-additive-expression> '-' <number-multiplicative-expression>

  <number-multiplicative-expression> :=
     <number-term> |
     <length-multiplicative-expression> '/' <length-term> |
     <length-multiplicative-expression> 'mod' <length-term>

  <number-term> := '(' <number-additive-expression> ')' | <number>

  <atomic-length> := <number><length-unit>
Note that 'mod' is used instead of '%' for modulus since it is very easy to get confused about whether '%' is acting as a unit or an operator. At least with 'mod' it always causes a parse error - invalid unit - in the otherwise ambiguous cases.

3.8. Special cases

Two common types of values fall outside the types described above: the value for font families and the hexadecimal color notation.

3.8.1. Font families

The 'font' and 'font-family' properties accept a comma-separated list of font families. Font families can either be the name of a certain font, or it can be one of five generic font families: 'serif', 'sans-serif', 'cursive','fantasy', and 'monospace'. Font family names are like strings, except that the quotes around them may be dropped but not always. Generic font family names are keywords and must not be quoted.

body { font-family: "Helvetica", "Univers", "Arial", sans-serif }

3.8.2. Colors

A color value can either be a keyword, a numerical RGB specification in a functional notation, or a numerical RGB specification in a hexadecimal notation. The hexadecimal notation is special shorthand format that allows compact color descriptions.

Example(s):

em { color: #F00 }

The CSS3 Color module defines the syntax of the hexadecimal notation.

4. Specified, computed, used, and actual values

The final value of a CSS3 property for a given element is the result of a four-step calculation: cascading and inheritance [!CSS3CASCADE] yields a value (the specified value), then relative values are computed into absolute values as far as possible without formatting the document (yielding the computed value), then the and finally transformed according to the limitations of the local environment (yielding the actual value).

4.1. Cascaded values

If there are several competing declarations for a given element/property combination, the cascading process will select a winning declaration which contains the cascaded value. See the Cascading and Inheritance module [!CSS3CASCADE] for more information.

Often, the cascaded value will be equal to the specified, computed and actual values. This is the case in example (a) in the table below.

If a cascaded value is set on a shorthand property, it is considered to be set on all individual properties. See example (b) in the table below.

When there is no winning declaration, there is no cascaded value. See example (c) in the table below.

4.2. Specified values

In the chain of computations from the cascaded value to the actual value, the specified value is the first value which is guaranteed to exist after inheritance has been performed. Furthermore, if the cascaded value is 'inherit' or 'initial', the specified value contains the inherited and initial value, respectively. See example (d) and (e) in the table below.

4.3. Computed values

Specified values may be absolute (i.e., they are not specified relative to another value, as in 'red' or '2mm') or relative (i.e., they are specified relative to another value, as in 'auto', '2em'). For absolute values, no processing is needed to find the computed value.

For relative values, on the other hand, computation is necessary to find the computed values: percentages must be multiplied by a reference value (each property defines which value that is), values with relative units (em, ex, px) must be made absolute by multiplying with the appropriate font or pixel size, 'auto' values must be computed by the formulas given with each property, certain keywords (e.g., 'smaller', 'bolder') must be replaced according to their definitions. See example (f), (g) and (h) in the table below.

Also, relative URIs are computed into absolute URIs at this stage. The computed value of invalid and absolute URIs is the same as the specified value.

4.4. Used values

Computed values are processed as far as possible without formatting the document. Some values, however, can only be determined when the document is being laid out. For example, if the width of an element is set to be a certain percentage of its containing block, the width cannot be determine until the width of the containing block has been determined. The used value is the result of taking the computed value and resolving any remaining dependencies into an absolute value.

4.5. Actual values

A used value is in principle ready to be used, but a user agent may not be able to make use of the value in a given environment. For example, a user agent may only be able to render borders with integer pixel widths and may therefore have to approximate the computed width. Also, the font size of an element may need adjustment based on the availability of fonts or the value of the 'font-size-adjust' property. The actual value is the computed value after adjustments have been made.

By probing the actual values of elements, much can be learned about how the document is laid out. However, not all information is recorded in the actual values. For example, the actual value of the 'page-break-after' property does not reflect whether there is a page break or not after the element. Similarly, the actual value of 'orphans' does not reflect how many orphan lines there is in a certain element. See examples (j) and (k) in the table below.

Example | Winning declaration | Property | Specified value | Computed value | Used value | Actual value
a | text-align: left | text-align | left | left | left | left
b | border-width: inherit | border-top-width, border-right-width, border-bottom-width, border-left-width | 4.2px | 4.2px | 4.2px | 4px
c | (no winning declaration) | width | auto (which is the initial value) | auto | 120px | 120px
d | list-style-position: inherit | list-style-position | inside | inside | inside | inside
e | list-style-position: initial | list-style-position | outside (which is the initial value) | outside | outside | outside
f | font-size: 1.2em | font-size | 1.2em | 14.1px | 14.1px | 14px
g | width: 80% | width | 80% | 80% | 354.2px | 354px
h | width: auto | width | auto | auto | 134px | 134px
i | height: auto | height | auto | auto | 176px | 176px
j | (no winning declaration) | page-break-after | auto (which is the initial value) | auto | auto | auto
k | orphans: 3 | orphans | 3 | 3 | 3 | 3

Acknowledgments

Comments and suggestions from Ian Hickson, David Baron, Edward Welbourne, Boris Zbarsky, Björn Höhrmann and Michael Day improved this module.

References

Normative references

[CSS21]
Bert Bos; et al. Cascading Style Sheets, level 2 revision 1. 11 April 2006. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2006/WD-CSS21-20060411
[CSS3CASCADE]
Håkon Wium Lie. CSS3 module: Cascading and inheritance. 19 February 2002. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2002/WD-css3-cascade-20020219
[CSS3COLOR]
Tantek Çelik; Chris Lilley. CSS3 Color Module. 14 May 2003. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2003/CR-css3-color-20030514
[CSS3FONT]
Michel Suignard; Chris Lilley. CSS3 module: Fonts. 2 August 2002. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2002/WD-css3-fonts-20020802
[CSS3SYN]
L. David Baron. CSS3 module: Syntax. 13 August 2003. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2003/WD-css3-syntax-20030813
[CSS3TEXT]
Elika J. Etemad. CSS3 Text Module. 27 June 2005. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2005/WD-css3-text-20050627

Other references

[CSS3NAMESPACE]
Peter Linss. CSS Namespace Enhancements (Proposal). 25 June 1999. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/1999/06/25/WD-css3-namespace-19990625
[RFC1738]
T. Berners-Lee; L. Masinter; M. McCahill. Uniform Resource Locators (URL). December 1994. Internet RFC 1738. URL: http://www.ietf.org/rfc/rfc1738.txt
[RFC1808]
R. Fielding. Relative Uniform Resource Locators. June 1995. Internet RFC 1808. (Obsoleted by RFC 3986) URL: http://www.ietf.org/rfc/rfc1808.txt

Index

  • Absolute length, #
  • Actual values, #
  • calc(<expression>), #
  • Cascaded values, #
  • color, #
  • Computed values, #
  • 'counter(<identifier>)', #
  • 'counter(<identifier>, <list-style-type>)', #
  • deg (degrees), #
  • em (grid)
    • definition of, #
  • em (unit), #
  • ex (unit), #
  • gd (grid)
    • definition of, #
  • generic font families, #
  • grad (grads), #
  • grid units, #
  • Hz (Hertz), #
  • kHz (kilohertz), #
  • <angle>
    • definition of, #
  • <counter>, definition of, #
  • <frequency>
    • definition of, #
  • <integer>, #
  • <length>, #
  • <non-negative integer>, #
  • <non-negative number>, #
  • <number>, #, #, #, #, #
  • <percentage>
    • definition of, #
  • <string>, definition of, #
  • <time>
    • definition of, #
  • ms (milliseconds), #
  • newline, #
  • pixel unit, #
  • px (pixel)
    • definition of, #
  • quad width, #
  • rad (radians), #
  • reference pixel, #
  • Relative length units, #
  • Resource Identifier (URI), #
  • root em, #
  • Specified values, #
  • s (seconds), #
  • turn, #
  • Uniform Resource Locator (URL), #
  • URI (Uniform Resource Identifier), #
  • URL (Uniform Resource Locator), #
  • Used values, #
  • vh
    • definition of, #
  • vm
    • definition of, #
  • vw
    • definition of, #
  • x-height, #


CSS3 Writing Modes Module

CSS Writing Modes Module Level 3

W3C Working Draft 02 December 2010

This version:
http://www.w3.org/TR/2010/WD-css3-writing-modes-20101202/
Latest version:
http://www.w3.org/TR/css3-writing-modes/
Previous version:
-
Editors:
Elika J. Etemad (Invited Expert)
Koji Ishii (Antenna House)
Shinyu Murakami (Antenna House)
Previous Editors:
Paul Nelson (Microsoft)
Michel Suignard (Microsoft)

Copyright © 2010 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

Abstract

This module specifies the text layout model in CSS and the properties that control it. It covers bidirectional and vertical text.

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

The (archived) public mailing list www-style@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “css3-writing-modes” in the subject, preferably like this: “[css3-writing-modes] …summary of comment…”

This document was produced by the CSS Working Group (part of the Style Activity).

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This is the first public working draft of the CSS Writing Modes module as a separate specification. The functionality was split off from the CSS Text module of 14 May 2003.

Table of Contents

  • 1. Introduction
    • 1.1. Introduction to Vertical Text
  • 2. Writing Modes and Terminology
  • 3. Inline Direction and Bidirectionality
    • 3.1. Specifying Directionality: the ‘direction’ property
    • 3.2. Embeddings and Overrides: the ‘unicode-bidi’ property
    • 3.3. Example of Bidirectional Text
    • 3.4. Box model for inline elements in bidirectional context
  • 4. Block Flow Direction: the ‘writing-mode’ property
    • 4.1. Box Layout in Vertical Writing Modes
  • 5. Line Orientation
    • 5.1. Orienting Text: the ‘text-orientation’ property
  • 6. Abstract Box Layout
    • 6.1. Logical vs Physical Dimensions
      • 6.1.1. Orthogonal Flows
    • 6.2. Logical vs Physical Directions
      • 6.2.1. Logical Directions
      • 6.2.2. Line-Relative Directions
      • 6.2.3. Abstract-to-Physical Mappings
      • 6.2.4. Purely Physical Properties
      • 6.2.5. The ‘caption-side’ property
  • 7. Glyph Composition: the ‘text-combine’ property
  • Acknowledgements
  • Appendix B: Bidi Rules for HTML
  • References
    • Normative references
    • Other references

1. Introduction

This section is non-normative.

This module defines support for various international writing directions, such as left-to-right (e.g., Latin scripts), right-to-left (e.g., Hebrew or Arabic), bidirectional (e.g., mixing Latin with Arabic) and vertical (e.g., Asian scripts).

Inherently bottom-to-top scripts are not handled in this version. See [UTN22] for an explanation of relevant issues.

1.1. Introduction to Vertical Text

In addition to extensions to CSS2.1's support for bidirectional text, this module introduces the rules and properties needed to support vertical text layout in CSS.

Unlike languages that use the Latin script which are primarily laid out horizontally, Asian languages such as Chinese and Japanese can be laid vertically. The Japanese example below shows the same text laid out horizontally and vertically. In the horizontal case, text is read from left to right, top to bottom. For the vertical case, the text is read top to bottom, right to left. Indentation from the left edge in the left-to-right horizontal case translates to indentation from the top edge in the top-to-bottom vertical case.

Comparison of vertical and horizontal Japanese

For Chinese and Japanese lines are ordered either right to left, while for Mongolian and Manchu left to right.

The change from horizontal to vertical writing can affect not just the layout, but also the typesetting. For example, the position of a punctuation mark within its spacing box can change from the horizontal to the vertical case, and in some cases alternate glyphs are used.

Vertical text that includes Latin script text or text from other scripts normally displayed horizontally can display that text in a number of ways. For example, Latin words can be rotated sideways, or each letter can be oriented upright.

Latin initialisms like GNP can appear either rotated 90° clockwise, or with the letters stacked upright.

Examples of Latin in vertical Japanese

In some special cases such as two-digit numbers in dates, text is fit compactly into a single vertical character box:

Diagram of showing the two-digit numbers of a date set halfwidth side-by-side in a vertical column of text

Example of horizontal-in-vertical two-digit numbers

Layouts often involve a mixture of vertical and horizontal elements:

Magazines often mix horizontal and vertical layout; for example, using one orientation for the main article text and a different one for sidebar or illustrative content.

Mixture of vertical and horizontal elements

Vertical text layouts also need to handle bidirectional text layout; clockwise-rotated Arabic, for example, is laid out bottom-to-top.

2. Writing Modes and Terminology

A writing mode in CSS is determined by the ‘writing-mode’, ‘direction’, and ‘text-orientation’ properties. It is defined primarily in terms of its inline base direction and block flow direction:

Latin-based writing mode

Mongolian-based writing mode

Han-based writing mode

The inline base direction is the primary direction in which content is ordered on a line and defines on which sides the "start" and "end" of a line are. The ‘direction’ property specifies the inline base direction of an element and, together with the ‘unicode-bidi’ property and the inherent directionality of any text content, determines the ordering of inline-level content within a line.

The block flow direction is the direction in which block-level boxes stack and the direction in which line boxes stack within a block container. The ‘writing-mode’ property determines the block flow direction.

A horizontal writing mode is one with horizontal lines of text, i.e. a downward or upward block flow. A vertical writing mode is one with vertical lines of text, i.e. a leftward or rightward block flow.

These terms should not be confused with vertical block flow (which is a downward or upward block flow) and horizontal block flow (which is leftward or rightward block flow). To avoid confusion, the CSS specifications avoid this latter set of terms.

Writing systems typically have one or two native writing modes. Some examples are:

  • Latin-based systems are typically written using a left-to-right inline direction with a downward (top-to-bottom) block flow direction.
  • Arabic-based systems are typically written using a right-to-left inline direction with a downward (top-to-bottom) block flow direction.
  • Mongolian-based systems are typically written using a top-to-bottom inline direction with a rightward (left-to-right) block flow direction.
  • Han-based systems are commonly written using a left-to-right inline direction with a downward (top-to-bottom) block flow direction, or a top-to-bottom inline direction with a leftward (right-to-left) block flow direction. Many magazines and newspapers will mix these two writing modes on the same page.

Some additional characteristics, the line orientation and glyph orientation, are primarily used to handle scripts placed in a non-native writing mode. The line orientation determines which side of the line is the "top" and thus which sides are under or over the line. This determines the interpretation of alignment in the transverse dimension of the line. It also determines the default glyph orientation for scripts in a non-native orientation. These characteristics are controlled by the ‘text-orientation’ property.

In the following example, two blocks elements (1 and 3) separated by an image (2) are presented in various flow writing modes.

Here is a diagram of horizontal writing mode (writing-mode: horizontal-tb):

Diagram of horizontal layout: blocks 1, 2, and 3 are stacked top-to-bottom

Here is a diagram for the right-to-left vertical writing mode commonly used in East Asia (writing-mode: vertical-rl):

Diagram of a right-to-left vertical layout: blocks 1, 2, and 3 are arranged side by side from right to left

And finally, here is a diagram for the left-to-right vertical writing mode used for Uighur and Mongolian (writing-mode: lr):

Diagram of left-to-right vertical layout: blocks 1, 2, and 3 are arranged side by side from left to right

See Unicode Technical Note #22 [UTN22] (HTML version) for a more in-depth introduction to writing modes and vertical text.

3. Inline Direction and Bidirectionality

While the characters in most scripts are written from left to right, certain scripts are written from right to left. In some documents, in particular those written with the Arabic or Hebrew script, and in some mixed-language contexts, text in a single (visually displayed) block may appear with mixed directionality. This phenomenon is called bidirectionality, or "bidi" for short.

The Unicode standard (Unicode Standard Annex #9) defines a complex algorithm for determining the proper ordering of bidirectional text. The algorithm consists of an implicit part based on character properties, as well as explicit controls for embeddings and overrides. CSS relies on this algorithm to achieve proper bidirectional rendering. The ‘direction’ and ‘unicode-bidi’ properties allow authors to specify how the elements and attributes of a document language map to this algorithm.

User agents that support bidirectional text must apply the Unicode bidirectional algorithm to every sequence of inline boxes uninterrupted by a forced (bidi class B) line break or block boundary. This sequence forms the "paragraph" unit in the bidirectional algorithm. The paragraph embedding level is set according to the value of the ‘direction’ property of the containing block rather than by the heuristic given in steps P2 and P3 of the Unicode algorithm.

Because the base directionality of a text depends on the structure and semantics of the document, these properties should in most cases be used only to map bidi information in the markup to its corresponding CSS styles. If a document language provides markup features to control bidi, authors and users should use those features and not specify CSS rules to override them.

The HTML 4 specification ([HTML401], section 8.2) defines bidirectionality behavior for HTML elements. The HTML 4 specification also contains more information on bidirectionality issues.

Because HTML UAs can turn off CSS styling, we advise HTML authors to use the HTML ‘dir’ attribute and <bdo> element to ensure correct bidirectional layout in the absence of a style sheet.

3.1. Specifying Directionality: the ‘direction’ property

Name: | direction
Value: | ltr | rtl
Initial: | ltr
Applies to: | all elements
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value

This property specifies the base directionality of text and elements on a line, and the directionality of embeddings and overrides (see ‘unicode-bidi’) for the Unicode bidirectional algorithm. In addition, it affects the ordering of table column layout, the direction of horizontal overflow, and the default alignment of text within a line, and other things that depend on the base inline base direction.

Values for this property have the following meanings:

ltr
Left-to-right directionality.
rtl
Right-to-left directionality.

The ‘direction’ property has no reordering in inline-level elements whose ‘unicode-bidi’ property's value is ‘normal’.

The value of the ‘direction’ property on the root element is also propagated to the initial containing block and, together with the ‘writing-mode’ property, determines the document's principal writing mode. (See below.)

Note that the ‘direction’ property of the HTML BODY element is not propagated to the viewport. That special behavior only applies to the background and overflow properties.

The ‘direction’ property, when specified for table column elements, is not inherited by cells in the column since columns are not the ancestors of the cells in the document tree. Thus, CSS cannot easily capture the "dir" attribute inheritance rules described in [HTML401], section 11.3.2.1.

3.2. Embeddings and Overrides: the ‘unicode-bidi’ property

Name: | unicode-bidi
Value: | normal | [ [ embed | isolate ] || [ plaintext | bidi-override ] ]
Initial: | normal
Applies to: | all elements, but see prose
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified value

Values for this property have the following meanings:

normal
The element does not open an additional level of embedding with respect to the bidirectional algorithm. For inline-level elements, implicit reordering works across element boundaries.
embed
If the element is inline-level, this value opens an additional level of embedding with respect to the bidirectional algorithm. The direction of this embedding level is given by the ‘direction’ property. Inside the element, reordering is done implicitly. This corresponds to adding a LRE (U+202A; for ‘direction: ltr’) or RLE (U+202B; for ‘direction: rtl’) at the start of the element and a PDF (U+202C) at the end of the element.
bidi-override
For inline-level elements this creates an override. For block-level, table-cell, table-caption, or inline-block elements this creates an override for inline-level descendants not within another block-level, table-cell, table-caption, or inline-block element. This means that inside the element, reordering is strictly in sequence according to the ‘direction’ property; the implicit part of the bidirectional algorithm is ignored. This corresponds to adding a LRO (U+202D; for ‘direction: ltr’) or RLO (U+202E; for ‘direction: rtl’) at the start of the element and a PDF (U+202C) at the end of the element.
isolate
For the purposes of the Unicode bidirectional algorithm, the contents of the element are considered to be inside a separate, independent paragraph, and for the purpose of bidi resolution in its containing bidi paragraph (if any), the element itself is treated as if it were an Object Replacement Character (U+FFFC). (If the element is broken across multiple lines, then each box of the element is treated as an Object Replacement Character.)
plaintext

For the purposes of the Unicode bidirectional algorithm, the base directionality of each "paragraph" for which the element is the containing block element is determined not by the element's computed ‘direction’ as usual, but by following rules P1, P2, and P3 of the Unicode bidirectional algorithm. However, if no direction-determining character is found in step P2, then the value of the ‘direction’ property is used instead. Note this value has no effect on inline elements.

The final order of characters in each block-level element is the same as if the bidi control codes had been added as described above, markup had been stripped, and the resulting character sequence had been passed to an implementation of the Unicode bidirectional algorithm for plain text that produced the same line-breaks as the styled text. In this process, non-textual entities such as images are treated as neutral characters, unless their ‘unicode-bidi’ property has a value other than ‘normal’, in which case they are treated as strong characters in the ‘direction’ specified for the element.

Please note that in order to be able to flow inline boxes in a uniform direction (either entirely left-to-right or entirely right-to-left), more inline boxes (including anonymous inline boxes) may have to be created, and some inline boxes may have to be split up and reordered before flowing.

Because the Unicode algorithm has a limit of 61 levels of embedding, care should be taken not to use ‘unicode-bidi’ with a value other than ‘normal’ unless appropriate. In particular, a value of ‘inherit’ should be used with extreme caution. However, for elements that are, in general, intended to be displayed as blocks, a setting of ‘unicode-bidi: isolate’ is preferred to keep the element together in case display is changed to inline (see example below).

The following example shows an XML document with bidirectional text. It illustrates an important design principle: document language designers should take bidi into account both in the language proper (elements and attributes) and in any accompanying style sheets. The style sheets should be designed so that bidi rules are separate from other style rules, and such rules should not be overridden by other style sheets so that the document language's bidi behavior is preserved.

3.3. Example of Bidirectional Text

In this example, lowercase letters stand for inherently left-to-right characters and uppercase letters represent inherently right-to-left characters. The text stream is shown in logical backing store order.

<HEBREW>
  <PAR>HEBREW1 HEBREW2 english3 HEBREW4 HEBREW5</PAR>
  <PAR>HEBREW6 <EMPH>HEBREW7</EMPH> HEBREW8</PAR>
</HEBREW>
<ENGLISH>
  <PAR>english9 english10 english11 HEBREW12 HEBREW13</PAR>
  <PAR>english14 english15 english16</PAR>
  <PAR>english17 <HE-QUO>HEBREW18 english19 HEBREW20</HE-QUO></PAR>
</ENGLISH>

Since this is arbitrary XML, the style sheet is responsible for setting the writing direction. This is the style sheet:

/* Rules for bidi */
HEBREW, HE-QUO  {direction: rtl; unicode-bidi: embed;}
ENGLISH         {direction: ltr; unicode-bidi: embed;}

/* Rules for presentation */
HEBREW, ENGLISH, PAR  {display: block;}
EMPH                  {font-weight: bold;}

The HEBREW element is a block with a right-to-left base direction, the ENGLISH element is a block with a left-to-right base direction. The PARs are blocks that inherit the base direction from their parents. Thus, the first two PARs are read starting at the top right, the final three are read starting at the top left. Please note that HEBREW and ENGLISH are chosen as element names for explicitness only; in general, element names should convey structure without reference to language.

The EMPH element is inline-level, and since its value for ‘unicode-bidi’ is ‘normal’ (the initial value), it has no effect on the ordering of the text. The HE-QUO element, on the other hand, creates an embedding.

The formatting of this text might look like this if the line length is long:

               5WERBEH 4WERBEH english3 2WERBEH 1WERBEH

                                8WERBEH 7WERBEH 6WERBEH

english9 english10 english11 13WERBEH 12WERBEH

english14 english15 english16

english17 20WERBEH english19 18WERBEH

Note that the HE-QUO embedding causes HEBREW18 to be to the right of english19.

If lines have to be broken, it might be more like this:

       2WERBEH 1WERBEH
  -EH 4WERBEH english3
                 5WERB

   -EH 7WERBEH 6WERBEH
                 8WERB

english9 english10 en-
glish11 12WERBEH
13WERBEH

english14 english15
english16

english17 18WERBEH
20WERBEH english19

Because HEBREW18 must be read before english19, it is on the line above english19. Just breaking the long line from the earlier formatting would not have worked. Note also that the first syllable from english19 might have fit on the previous line, but hyphenation of left-to-right words in a right-to-left context, and vice versa, is usually suppressed to avoid having to display a hyphen in the middle of a line.

3.4. Box model for inline elements in bidirectional context

For each line box, UAs must take the inline boxes generated for each element and render the margins, borders and padding in visual order (not logical order).

When the element's ‘direction’ property is ‘ltr’, the left-most generated box of the first line box in which the element appears has the left margin, left border and left padding, and the right-most generated box of the last line box in which the element appears has the right padding, right border and right margin.

When the element's ‘direction’ property is ‘rtl’, the right-most generated box of the first line box in which the element appears has the right padding, right border and right margin, and the left-most generated box of the last line box in which the element appears has the left margin, left border and left padding.

4. Block Flow Direction: the ‘writing-mode’ property

Name: | writing-mode
Value: | horizontal-tb | vertical-rl | vertical-lr
Initial: | horizontal-tb
Applies to: | All elements except table row groups, table column groups, table rows, and table columns
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value

This property sets the block flow direction. Possible values:

horizontal-tb
Top-to-bottom block flow. The writing mode is horizontal.
vertical-rl
Right-to-left block flow. The writing mode is vertical.
vertical-lr
Left-to-right block flow. The writing mode is vertical.

SVG1.1 [SVG11] defines some additional values: ‘lr’, ‘lr-tb’, ‘rl’, ‘rl-tb’, ‘tb’, and ‘tb-rl’. These values are deprecated in any context except SVG1 documents. Implementations that wish to support them in the context of CSS must treat these values as follows:

SVG1 | CSS
lr | horizontal-tb
lr-tb
rl
tb | vertical-rl
tb-rl

In SVG1.1, these values set the inline progression direction, in other words, the direction the current text position advances each time a glyph is added. This is a geometric process that happens after bidi reordering, and thus has no effect on the interpretation of the ‘direction’ property (which is independent of ‘writing-mode’). (See Relationship with bidirectionality. [SVG11]) There are varying interpretations on whether this process causes "writing-mode: rl" to merely shift the text string or reverse the order of all glyphs in the text.

See this demo to check out your implementation's interpretation! (Note that most SVG implementations don't support the ‘direction’ property, and thus your results may be skewed on that account. Examine the red line of text: if the numbers are not in reverse order, your implementation doesn't support "direction: rtl".)

The ‘writing-mode’ property determines the direction of block flow. This determines the progression of block-level boxes in a block formatting context; the progression of line boxes in a block container that contains inlines; and the progression of rows in a table. As a result it also determines which side of a box is its before edge (i.e. the edge that comes earlier in the progression) and which side is its after edge (i.e. the edge that comes later in the progression).

The ‘writing-mode’ property, by virtue of determining the stacking direction of line boxes, determines whether line boxes and thus the writing mode of text are horizontal or vertical. However, it does not determine the orientation of the line boxes' contents or the start and end sides of the line. See Line orientation.

When set on the root element, the ‘writing-mode’ property together with the ‘direction’ property determines the principal writing mode of the document. This writing mode is used, for example, to determine the default page progression direction. See [CSS3PAGE] The ‘writing-mode’ value of the root element is also propagated to the initial containing block and sets the block flow direction of the initial block formatting context.

Note that the ‘direction’ property of the HTML BODY element is not propagated to the viewport. That special behavior only applies to the background and overflow properties.

If an element has a different block flow direction than its containing block:

  • If the element has a specified ‘display’ of ‘inline’, its ‘display’ computes to ‘inline-block’. [CSS21]
  • If the element has a specified ‘display’ of ‘run-in’, its ‘display’ computes to ‘block’. [CSS21]
POWERED BY HeroNote

If such an element is a block container, then it establishes a new block formatting context.

The content of replaced elements do not rotate due to the writing mode: images, for example, remain upright. However replaced content involving text (such as MathML content or form elements) should match the replaced element's writing mode and line orientation if the UA supports such a vertical writing mode for the replaced content.

4.1. Box Layout in Vertical Writing Modes

CSS box layout in vertical writing modes is analogous to layout in the horizontal writing modes, following the principles outlined below. See Abstract Box layout for a more complete discussion.

Layout calculation rules (such as those in CSS2.1, Section 10.3) that apply to the horizontal dimension in horizontal writing modes instead apply to the vertical dimension in vertical writing modes. Likewise, layout calculation rules (such as those in CSS2.1, Section 10.6) that apply to the vertical dimension in horizontal writing modes instead apply to the horizontal dimension in vertical writing modes. Thus:

  • Layout rules that refer to the width use the height instead, and vice versa.

  • Layout rules that refer to the ‘*-left’ and ‘*-right’ box properties (border, margin, padding) use ‘*-top’ and ‘*-bottom’ instead, and vice versa.

    Which side of the box the property applies to doesn't change: only which values are inputs to which layout calculations changes. The ‘margin-left’ property still affects the lefthand margin, for example; however in a ‘vertical-rl’ writing mode it takes part in margin collapsing in place of ‘margin-bottom’.

  • Layout rules that depend on the ‘direction’ property to choose between left and right (e.g. overflow, overconstraint resolution, the initial value for ‘text-align’, table column ordering) are abstracted to the start and end sides and applied appropriately.

For features such as text alignment, floating, and list marker positioning, that primarily reference the left or right sides of the line box or its longitudinal parallels and therefore have no top or bottom equivalent, the line left and line right sides are used as the reference for the left and right sides respectively. See Line-Relative Directions for details.

Likewise for features such as underlining, overlining, and baseline alignment (the unfortunately-named ‘vertical-align’), that primarily reference the top or bottom sides of the linebox or its transversal parallels and therefore have no left or right equivalent, the over and under sides are used as the reference for the top and bottom sides respectively. (See Line-Relative Directions.)

5. Line Orientation

Every line box has an orientation. Whether its orientation is horizontal or vertical is determined by the ‘writing-mode’ property. Given that, which side is its "top", or over edge, is determined by the ‘text-orientation’ property on its containing block, and is independent of the block flow direction.

In addition to its over (ascender side) and under (descender side) edges, a line box, even a vertically-oriented one, also has a "left" and "right" side, which we will call the line left and line right sides of the box to distinguish from the physical left and physical right sides of the box.

Line orientation compass

The start edge of a box is nominally the edge from which text of its inline base direction will start. For boxes with a used ‘direction’ value of ‘ltr’, this means the line left edge. For boxes with a used ‘direction’ value of ‘rtl’, this means the line right edge. The edge opposite the start edge is the end edge.

These directional mappings exist even for boxes that do not contain any line boxes: they are calculated by the values of the ‘writing-mode’, ‘text-orientation’, and ‘direction’ properties only.

Note that determining the start and end edges of a box depends not only on its ‘writing-mode’ and ‘direction’ properties, but also its ‘text-orientation’ property.

Typical orientation in vertical

Line orientation with ‘text-orientation: rotate-left’

Note also that while the over and under directions often map to the same directions as before and after respectively, this mapping is reversed for some combinations of ‘writing-mode’ and ‘text-orientation’.

5.1. Orienting Text: the ‘text-orientation’ property

Name: | text-orientation
Value: | vertical-right | upright | rotate-right | rotate-left | rotate-normal | auto
Initial: | vertical-right
Applies to: | all elements except table row groups, rows, column groups, and columns
Inherited: | yes
Percentages: | N/A
Media: | visual
Computed value: | specified value

This property specifies the orientation of characters in a non-native ‘writing-mode’ and sets the orientation of the line. Current values only have an effect in vertical writing modes. Values have the following meanings:

vertical-right

In vertical writing modes, grapheme clusters from scripts that do not have an intrinsic vertical orientation are rotated 90° clockwise from their standard orientation in horizontal text. When available, vertical glyph variants and vertical font metrics are used to set all punctuation and characters from any script that is not rotated. This value is typical for layout of primarily vertical-script text.

upright

In vertical writing modes, grapheme clusters that do not have an intrinsic vertical orientation are rendered upright, i.e. in their standard horizontal orientation. Shaping characters are shaped in their isolated forms. When available, vertical glyph variants and vertical font metrics are used to set the text. The UA should synthesize vertical font metrics for grapheme clusters that do not have any.

For the purposes of bidi reordering, this value causes all characters to be treated as strong LTR. This value causes the used value of ‘direction’ to be ‘ltr’.

rotate-right

In vertical writing modes, this causes text to be set as if in a horizontal layout (using horizontal glyph variants and metrics), but rotated 90° clockwise. This value is typical for ‘vertical-rl’ text in a primarily horizontal-script document.

rotate-left

In vertical writing modes, this causes text to be set as if in a horizontal layout (using horizontal glyph variants and metrics), but rotated 90° counter-clockwise. This value is typical for ‘vertical-lr’ text in a primarily horizontal-script document.

If set on a non-replaced inline whose parent is not ‘rotate-left’, this forces ‘isolate’ to be added to the computed value of ‘unicode-bidi’. Layout of text is exactly as for ‘rotate-right’ except that the entire text content and baseline table of the element is mirrored: each box of the inline is mirrored around a vertical axis such that its content box does not move. (However the contents of atomic inlines are not mirrored; only their alignment is changed.) Similarly, if a child of the element has a ‘text-orientation’ value other than ‘rotate-left’, an analogous transformation is applied.

rotate-normal

This value is equivalent to ‘rotate-right’ in ‘vertical-rl’ writing mode and equivalent to ‘rotate-left’ in ‘vertical-lr’ writing mode.

auto

[SVG11] defines ‘glyph-orientation-vertical’ and ‘glyph-orientation-horizontal’ properties that were intended to control text orientation. These properties are deprecated and do not apply to non-SVG elements. If an implementation supports these properties, the ‘auto’ value when set on SVG elements indicates that the SVG ‘glyph-orientation-vertical’ and ‘glyph-orientation-horizontal’ behavior control the layout of text. Such UAs must set ‘text-orientation: auto’ on all SVG text content elements in their default UA style sheet for SVG.

In all other contexts, and for implementations that do not support the glyph orientation properties, the ‘auto’ behavior is the same as for ‘vertical-right’.

Baseline alignment is not yet defined.

Add section explaining native script orientations. Note that all wide characters are treated the same as ideographic. Link to definition of grapheme clusters in [UAX29].

Add appendix that describes interaction with OpenType features and font layout?

6. Abstract Box Layout

[CSS21] defines the box layout model of CSS in detail. However, it only defines the box model for the ‘horizontal-tb’ writing mode. CSS box layout in writing modes other than ‘horizontal-tb’ is analogous to the box layout defined in CSS2.1 if boxes and dimensions are abstracted and remapped appropriately. This module defines the following abstract directional and dimensional terms and their mappings in order to define box layout for other writing modes:

6.1. Logical vs Physical Dimensions

block flow dimension
The dimension perpendicular to the flow of text with in a line, the vertical dimension in horizontal writing modes, and the horizontal dimension in vertical writing modes.
inline dimension
The dimension parallel to the flow of text within a line, i.e. the horizontal dimension in horizontal writing modes, and the vertical dimension in vertical writing modes.
inline-axis
The axis in the block flow dimension, i.e. the vertical axis in horizontal writing modes and the horizontal axis in vertical writing modes.
block-axis
The axis in the inline dimension, i.e. the horizontal axis in horizontal writing modes and the vertical axis in vertical writing modes.
length or logical height
A measurement in the block flow dimension: refers to the physical height (vertical dimension) in horizontal writing modes, and to the physical width (horizontal dimension) in vertical writing modes.
measure or logical width
A measurement in the inline dimension: refers to the physical width (horizontal dimension) in horizontal writing modes, and to the physical height (vertical dimension) in vertical writing modes. (The term measure derives from its use in typography.)

Certain properties behave logically as follows:

  • The first and second values of the ‘border-spacing’ property represent spacing between columns and rows respectively, not necessarily the horizontal and vertical spacing respectively. [CSS21]
  • The ‘line-height’ property always refers to the logical height. [CSS21]

The height properties (‘height’, ‘min-height’, and ‘max-height’) refer to the physical height, and the width properties (‘width’, ‘min-width’, and ‘max-width’) refer to the physical width. However, the rules used to calculate box dimensions and positions are logical.

For example, the calculation rules in CSS2.1 Section 10.3 are used for the inline dimension measurements: the logical width (which could be either the physical width or physical height) and the start and end margins, padding, and border. Likewise the calculation rules in CSS2.1 Section 10.6 are used for measurements in the block dimension. [CSS21]

As a corollary, percentages on the margin and padding properties, which are calculated with respect to the containing block width regardless of their dimension, are calculated with respect to the logical width of the containing block.

6.1.1. Orthogonal Flows

When an element has a different ‘writing-mode’ from its containing block two cases are possible:

  • The two writing modes are parallel to each other. (For example, ‘vertical-rl’ and ‘vertical-lr’).
  • The two writing modes are perpendicular to each other. (For example, ‘horizontal-tb’ and ‘vertical-rl’).

To handle the second case, for the purposes of calculating the layout of the box, the dimensions corresponding to the logical height and logical width of the containing block are determined using the writing mode of the box under consideration, not the writing mode of the element associated with the containing block.

What's a reasonable way of calculating ‘auto’ logical widths? The fallout of the above statements is not reasonable. Three good options are: use the max-content size; use 100vh margin-box; use the same logical width that would be calculated if the block flows were parallel.

6.2. Logical vs Physical Directions

The terms "left", "right", "top", and "bottom" are always interpreted physically, i.e. with respect to the page independent of writing mode. Two abstract mappings are possible for these directions: logical and line-relative. Which one is chosen depends on whether the usage is primarily with respect to the block, or primarily with respect to the line box.

6.2.1. Logical Directions

The logical directions are before, after, start, and end. In an LTR ‘horizontal-tb’ writing mode, they correspond to the top, bottom, left, and right directions, respectively.

An English (LTR-TB) block:

                  <---- width / logical width --->

                             top side/
                            before side
                  +------------------------------+                  A
      left side/  |   ---inline direction --->   |  right side/     |
      start side  |  |                           |  end side        |
                  |  | block      * horizontal * |                height/
                  |  | direction  *writing mode* |            logical height
                  |  V                           |                  |
                  +------------------------------+                  V
                             bottom side/
                              after side

A vertical Japanese block (TTB-RL):

                  <--- width / logical height --->

                             top side/
                            start side
                  +------------------------------+                  A
      left side/  |    <---block direction---    |  right side/     |
      after side  |                           |  |  before side     |
                  |  *  vertical  *     inline|  |                height/
                  |  *writing mode*  direction|  |             logical width
                  |                           V  |                  |
                  +------------------------------+                  V
                            bottom side/
                             end side

Logical directions are calculated with respect to the writing mode of the element and used to abstract layout related to padding and border properties. For example, if an element had computed values of ‘direction: ltr; writing-mode: vertical-lr; text-orientation: vertical-right’, ‘padding-top’ would give its start padding, and ‘padding-left’ would give its before padding.

Logical directions are calculated with respect to the writing mode of the parent of the element and used to abstract layout related to the margin properties and the ‘top’, ‘bottom’, ‘left’, and ‘right’ properties. (For the root element, which has no parent, the values of the writing mode of the element is used instead.)

The margin collapsing rules apply exactly with the before margin substituted for the top margin and the after margin substituted for the bottom margin. Similarly the padding and border on the same side as the before margin is substituted for the top padding and border, and the padding and border on the same side as the after margin for the bottom padding and border. Note this means only before and after margins ever collapse.

The parent element is used instead of the containing block, because the benefit of using the containing block is very rare, but the cost to implement it is rather high for implementations that do logical-physical mapping at cascade time.

The start and end directions are also used for inline layout as follows:

  • The initial value of the ‘text-align’ property aligns to the start edge of the line box.
  • The ‘text-indent’ property indents from the start edge of the line box.

6.2.2. Line-Relative Directions

The line-relative directions are over, under, line-left, and line-right. In an LTR ‘horizontal-tb’ writing mode, they correspond to the top, bottom, left, and right directions, respectively.

The line right and line left directions are calculated with respect to the writing mode of the element and used to interpret the ‘left’ and ‘right’ values of the following properties:

  • the ‘text-align’ property [CSS21]

The line right and line left directions are calculated with respect to the writing mode of the containing block of the element and used to interpret the ‘left’ and ‘right’ values of the following properties:

  • the ‘float’ property [CSS21]
  • the ‘clear’ property [CSS21]

The over and under directions are calculated with respect to the writing mode of the element and used to define the interpretation of the "top" (over edge) and "bottom" (under edge) of the line box as follows:

  • For the ‘vertical-align’ property, the "top" of the line box is the over edge; the "bottom" of the line box is the under edge. Positive length and percentage values shift the baseline towards the over edge. [CSS21]
  • For the ‘text-decoration’ property, the underline is drawn on the under side of the text; the overline is drawn on the over side of the text. [CSS21] Note that the CSS Text Module defines this in more detail and provides additional controls for controlling the position of underlines and overlines. [CSS3TEXT]

6.2.3. Abstract-to-Physical Mappings

The following table summarizes the abstract-to-physical mappings:

Abstract-Physical Mapping
‘writing-mode’ | ‘horizontal-tb’ |  | ‘vertical-rl’ |  |  |  | ‘vertical-lr’
‘text-orientation’ | — |  | ‘rotate-left’ |  | *right |  | ‘rotate-left’ |  | *right
‘direction’ | ‘ltr’ | ‘rtl’ | ‘ltr’ | ‘rtl’ | ‘ltr’ | ‘rtl’ | ‘ltr’ | ‘rtl’ | ‘ltr’ | ‘rtl’
length | height |  | width
measure | width |  | height
before | top |  | right |  |  |  | left
after | bottom |  | left |  |  |  | right
start | left | right | bottom | top | top | bottom | bottom | top | top | bottom
end | right | left | top | bottom | bottom | top | top | bottom | bottom | top
over | top |  | left |  | right |  | left |  | right
under | bottom |  | right |  | left |  | right |  | left
line-left | left |  | bottom |  | top |  | bottom |  | top
line-right | right |  | top |  | bottom |  | top |  | bottom

6.2.4. Purely Physical Properties

The following values are purely physical in their definitions and do not respond to changes in writing mode:

  • all values of ‘background-repeat’ other than ‘repeat-y’ and ‘repeat-x’ (described above)
  • the ‘rect()’ notation of the ‘clip’ property [CSS21]
  • the offsets of the ‘box-shadow’ and ‘text-shadow’ properties

6.2.5. The ‘caption-side’ property

This module introduces two new values to the ‘caption-side’ property: ‘before’ and ‘after’, which position the caption before and after the table box, respectively. For tables with ‘horizontal-tb’ writing mode, they are equivalent to the existing ‘top’ and ‘bottom’ values, respectively. [CSS21]

Implementations that only support the ‘top’ and ‘bottom’ values of the ‘caption-side’ property must treat them as ‘before’, when the table is in a vertical writing mode.

For implementations that support side captions (i.e. the ‘left’ and ‘right’ values), this module also introduces the ‘start’ and ‘end’ values, which behave similarly and which position the caption on the start and end sides of the table box, calculated with respect to the writing mode of the table element. For such implementations, the ‘top’ and ‘bottom’ values must place the caption on the top and bottom sides of the table box, respectively.

7. Glyph Composition: the ‘text-combine’ property

Name: | text-combine
Value: | none | [ horizontal <number>? ]
Initial: | none
Applies to: | non-replaced inline elements
Inherited: | no
Percentages: | N/A
Media: | visual
Computed value: | specified value

This property allows the combination of multiple characters into the space of a single character. For text layout purposes, e.g. bidi ordering, line-breaking, emphasis marks, text-decoration, etc. the resulting composition is treated as a single glyph representing the Object Replacement Character U+FFFC. Values have the following meanings:

none
No special processing.
horizontal

In vertical writing mode, attempt to display the text contents of the element horizontally within the vertical line box, ideally within the space of one ideographic character (1em square), as follows:

If the UA has compressed glyphs available for the contents of the element, then it should use those glyphs to attempt sizing the contents to 1em square. For example, a two digit number should use halfwidth or proportional glyphs, a three-digit number use 1/3-em glyphs (if available, else halfwidth glyphs), etc. The glyphs are stacked horizontally (similar to the contents of an inline-box with a horizontal writing mode and a line-height of 1em) and the baseline of the resulting composition chosen such that it is centered between the content edges of its parent inline box.

If the size of the composed glyph exceeds the element's used line-height, then { the UA may scale the contents to fit (else overflow the line) | the contents are instead rendered as if ‘text-combine’ were ‘none’ }

In horizontal mode, or if the number of grapheme clusters in the element exceeds the number specified (if any), this value is equivalent to ‘none’.

In East Asian documents, the ‘text-combine: upright’ effect is often used to display Latin-based strings such as components of a date or letters of an initialism, always in a horizontal writing mode regardless of the writing mode of the line:

Diagram of tate-chu-yoko, showing the two digits of a date set halfwidth side-by-side in a vertical column of text

Example of horizontal-in-vertical tate-chu-yoko

In Japanese, this effect is known as tate-chu-yoko.

Some people have requested a way to have numbers automatically text-combine'd. Maybe a text-auto-combine property? Note that whether a number should be tate-chu-yoko'd is often context-sensitive: this would give very weird results when applied to an arbitrary paragraph.

Acknowledgements

John Daggett, Martin Heijdra, Paul Nelson, Michel Suignard, Steve Zilles

Appendix B: Bidi Rules for HTML

The style sheet rules that would achieve the bidi behaviors specified in [HTML401] for the HTML Strict doctype are given below:

/* HTML dir attribute creates an embedding */
*[dir="ltr"]    { direction: ltr; unicode-bidi: embed; }
*[dir="rtl"]    { direction: rtl; unicode-bidi: embed; }

/* BDO element creates an override */
bdo[dir="ltr"]  { direction: ltr; unicode-bidi: bidi-override; }
bdo[dir="rtl"]  { direction: rtl; unicode-bidi: bidi-override; }

/* HTML4.01:8.2.6 - preserve bidi behavior if 'display' is changed */
html, body,
div, address, blockquote, p,
ul, ol, li, dl, dt, dd,
fieldset, form,
h1, h2, h3, h4, h5, h6,
{ unicode-bidi: isolate; }

References

Normative references

[CSS21]
Bert Bos; et al. Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification. 8 September 2009. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2009/CR-CSS2-20090908
[SVG11]
Erik Dahlström; et al. Scalable Vector Graphics (SVG) 1.1 (Second Edition). 22 June 2010. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2010/WD-SVG11-20100622
[UAX29]
Mark Davis. Text Boundaries. 25 March 2005. Unicode Standard Annex #29. URL: http://www.unicode.org/unicode/reports/tr29/tr29-9.html

Other references

[CSS3PAGE]
Melinda Grant; Håkon Wium Lie. CSS3 Module: Paged Media. 10 October 2006. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2006/WD-css3-page-20061010
[CSS3TEXT]
Paul Nelson; Elika J. Etemad. CSS Text Level 3. 6 March 2007. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2007/WD-css3-text-20070306
[HTML401]
David Raggett; Ian Jacobs; Arnaud Le Hors. HTML 4.01 Specification. 24 December 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-html401-19991224
[UTN22]
Elika J. Etemad. Robust Vertical Text Layout. 25 April 2005. Unicode Technical Note #22. URL: http://unicode.org/notes/tn22/


Superseded- user interface for CSS3

User Interface for CSS3

Superseded - 2 August 2002

This version:
http://www.w3.org/TR/2002/WD-css3-userint-20020802
Superseded by:
http://www.w3.org/TR/css3-ui
Latest version:
http://www.w3.org/TR/css3-userint
Previous version:
http://www.w3.org/TR/2000/WD-css3-userint-20000216

Copyright © 2002 W3C ® (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.

Status of this document

POWERED BY HeroNote

This document has been superseded. "User interface for CSS3" was a working draft of the CSS working group [member-only link]. Much of the functionality has been incorporated into a different series of drafts, "CSS3 module: basic user interface".

A list of current W3C Recommendations and other technical documents can be found at http://www.w3.org/TR.


The CSS 'Reader' Media Type

W3C Working Draft 24 February 2004

This version:
http://www.w3.org/TR/2004/WD-css3-reader-20040224
Latest version:
http://www.w3.org/TR/css3-reader
Previous version:
none
Editors:
Bert Bos (W3C), <bert@w3.org>

Copyright © 2004 W3C ® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.

Abstract

This is the first draft of the 'reader' media type. It is published to get some early feedback, especially on whether 'reader' is necessary and implementable.

'Reader' is a keyword for use in Media Queries [MEDIAQ]. When a Media Query that includes the 'reader' keyword is attached to (a link to) a style sheet, it indicates that that style sheet is designed to be used by a "reader" device (typically a screen reader), that both displays and speaks a document at the same time. It may also display the document and render it in braille at the same time, or do all three.

Media Queries (and thus 'reader') can be used in documents in HTML [HTML401], XML [XML10], SVG [SVG10], CSS [CSS21] and other formats, wherever they link to a style sheet, and potentially also in links to other resources. (But the latter is not treated in this specification.)

Status of this document

This section describes the status of this document at the time of its publication. Other documents may supersede it. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress." Its publication does not imply endorsement by the W3C membership. Implementations for the purpose of experimenting with the specification are welcomed, as long as they are clearly marked as experimental.

This document is a working draft of the CSS Working Group which is part of the style activity (see summary).

Comments on and discussions of this draft can be sent to the (archived) public mailing list www-style@w3.org (see instructions). W3C Members can also send comments directly to the CSS working group.

Patent disclosures relevant to CSS may be found on the Working Group's public patent disclosure page.

This is the first draft in this series ("css3-reader").

Table of contents

  • 1. Dependencies on other modules
  • 2. Introduction
  • 3. The 'reader' media type
  • 4. CSS features that apply to 'reader'
  • 5. Test suite
  • 6. Profiles
  • 7. Conformance
  • Acknowledgments
  • Normative references
  • Other references

1. Dependencies on other modules

This CSS3 module depends on the following other CSS specifications:

  • CSS 2.1 [CSS21]
  • Media Queries [MEDIAQ]

2. Introduction

HTML [HTML401], XML [XML10], SVG [SVG10], CSS [CSS21] and other formats can link to one or more style sheets that help in specifying the way a document is rendered for a human reader. Media Queries [MEDIAQ] can be attached to those links to indicate for what type of device or media the style sheet is designed, e.g., big screen with color, small monochrome screen, printer, slide projector or speech synthesizer.

E.g., an HTML4 document can link to a style sheet for use on (computer) screens and another for use on printers like this:

<html>
 <head>
  <title>My HTML document</title>
  <link rel="stylesheet" media="screen" href="my-screen-style.css">
  <link rel="stylesheet" media="print" href="my-print-style.css">
 </head>
 <body>
  ...
 </body>
</html>

The following example CSS style sheet links to another style sheet for printing and includes style rules that apply to a slide projection:

@import "my-print-style.css" print;

@media projection {
  h1 { page-break-before: always }
  h2 { color: red }
  ...
}

Media Queries contain a media type ('screen', 'print', 'projection', 'speech', etc.) optionally followed by further constraints ('min-width', 'max-width', 'color', etc.). 'Reader' is one such media type, applying to devices like screen readers, that display a document visually and read it with the help of a speech synthesizer at the same time.

The following is an XML document in some hypothetical format, that includes the standard style sheet Processing Instruction (the "style PI") [XMLSTYLE] to link to two style sheets, one for rendering on color screens in a window that is less then 400 pixels wide and another for readers that have a monitor in portrait mode:

<?xml-stylesheet href="style1.css" type="text/css"
  media="screen and (color) and (max-width: 400px"?>
<?xml-stylesheet href="style2.css" type="text/css"
  media="reader and (max-device-ratio: 1/1)"?>
<doc>
  ...
</doc>

3. The 'reader' media type

The keyword 'reader' is a "media type" as defined by Media Queries [MEDIAQ]. It can be used in all places where Media Queries can be used (including LINK elements in HTML, the style PI in XML and @import/@media in CSS).

'Reader' is exclusive with all other media types defined in Media Queries, except with the keyword 'all'. That is, a user agent that applies style rules marked as being for a 'reader' must not at the same time apply style rules marked for some other media.

However, a single user agent might operate in different "modes" at different times or even at the same time in different windows (different "canvasses"). A user agent can, e.g., provide a print preview (using style rules for the 'print' media) and a simulation of a handheld device (using style rules for 'handheld').

POWERED BY HeroNote

This specification does not define which UAs must use which media type. UAs (or the users using them) can select which media type best fits them and the environment in which they run. The following are therefore only informative guidelines:

The 'reader' media type typically is used by a UA that:

  • is a "screen reader" (often designed as an accessibility aid);
  • displays a document on screen and speaks what is on screen;
  • either scrolls the screen automatically in sync with the speech; or
  • waits for the user to scroll;
  • allows the user to indicate the part to be spoken, by pointing or by using fast-forward/fast-reverse or similar functions;
  • instead of or in addition to speaking, it may also render the displayed text on a dynamic braille device.

Do we need a pseudo-class for the element currently being spoken? (Karaoke!)

4. CSS features that apply to 'reader'

The CSS features that apply to the 'reader' media type are all properties and other features that apply to the following media groups. See section 7.3.1 "Media Groups" of CSS 2.1 [CSS21] for definitions of these groups. [No section to point to in CSS3 yet?]

 | continuous / paged? | visual / audio / speech / tactile? | grid / bitmap? | interactive / static?
reader | continuous | all | both | interactive

All property definitions in CSS3 modules include a line that specifies to which of these media groups the property applies.

Note that 'reader' can be used both with bitmapped and with grid-based screens. To distinguish between the two types, a designer can use the 'grid' media feature as defined by Media Queries [MEDIAQ].

E.g., a style sheet might be written as follows:

@media reader and (grid: 0) {
    /* styles for bitmapped displays */
    ...
}
@media reader and (grid: 1) {
    /* Styles for grid-based displays */
    ...
}

Can it be "static" as well? A reader that just starts reading at the top and continues until the end of the document, scrolling the display as needed, without user interaction? Maybe not important.

5. Test suite

[TBD]

6. Profiles

[TBD]

7. Conformance

[TBD]

Acknowledgments

Joe Clark (see message on www-style and [FIR])

Normative references

[CSS21]
Bert Bos; Tantek Çelik; Ian Hickson; Håkon Wium Lie. Cascading Style Sheets, level 2 revision 1. 15 September 2003. W3C Working Draft. (Work in progress) URL: http://www.w3.org/TR/2003/WD-CSS21-20030915
[MEDIAQ]
Håkon Wium Lie; Tantek Çelik; Daniel Glazman. Media queries. 8 July 2002. W3C Candidate Recommendation. (Work in progress.) URL: http://www.w3.org/TR/2002/CR-css3-mediaqueries-20020708

Other references

[FIR]
Joe Clark. "Facts and Opinion About Fahrner Image Replacement" in: A List Apart. Issue No. 160. 20 October 2003. URL: http://www.alistapart.com/articles/fir/
[HTML401]
Raggett, D.; Le Hors, A.; Jacobs, I.. HTML 4.01 Specification. Dec 1999. W3C Recommendation. URL: http://www.w3.org/TR/1999/REC-html401-19991224
[SVG10]
Various. Scalable Vector Graphics (SVG) 1.0 Specification. Sep 2001. W3C Recommendation. URL: http://www.w3.org/TR/2001/REC-SVG-20010904
[XML10]
Tim Bray; Jean Paoli; C. M. Sperberg-McQueen; Eve Maler. Extensible Markup Language (XML) 1.0 (Second Edition). Oct 2000. W3C Recommendation. URL: http://www.w3.org/TR/2000/REC-xml-20001006
[XMLSTYLE]
J. Clark. Associating Style Sheets with XML documents. 29 June 1999. W3C Recommendation. URL: http://www.w3.org/TR/xml-stylesheet


Check Update

CSS3 Specification

File Name: CSS3.chm

Current Version: September 01,2011

Check Update: http://www.HeroNote.com/files/CSS3.htm


[File List]

 default.css
index.htm
logo-WD.png
NOTE.gif
w3c_home.png
W3C-WD.css
compound_transform.png
default.css
index.htm
transform1.png
W3C-WD.css
default.css
index.htm
animation1.png
default.css
index.htm
sandwich.png
bg-pos.png
bg-repeat.png
bg-space.png
border.png
border-image.png
borderresult.png
borderstyles.png
box.png
box-break.png
corner.png
corner-large-mix.png
default.css
groovy-border-image-slice.png
index.htm
shadow-inner-round.png
shadow-inner-spread-round.png
shadow-inner-spread-square.png
shadow-inner-square.png
shadow-outer-round.png
shadow-outer-spread-round.png
shadow-outer-spread-square.png
shadow-outer-square.png
slice.png
smooth-radius.png
spread-blur.png
transition-region.png
anonymous.png
box.png
box-intro.png
default.css
diagonal-headings.png
float2p.png
floatclear.png
floateg.png
index.htm
overflow1.png
overflow2.png
stack.png
supercal.png
default.css
index.htm
logo-CR.png
W3C-CR.css
default.css
index.htm
logo-PR.png
W3C-PR.css
default.css
index.htm
aaaaaa.png
aaaaaa-diacritics.png
beforefontsizeadjust.png
cursiveexamples.png
default.css
familyvsfacename.png
fantasyexamples.png
final-ligature.png
fontsizeadjust.png
hiraginoweights.png
index.htm
lamaleflig.png
localizedfamilynames.png
minchovsgothic.png
monospaceexamples.png
optimaweights.png
realvsfakeitalics.png
sansserifexamples.png
serifexamples.png
serifvssansserif.png
universwidths.png
weightwidthvariations.png
crop.png
default.css
index.htm
default.css
index.htm
default.css
figure1.jpg
figure2.jpg
index.htm
Yeeaahh.png
Yeeaahh_grid.png
default.css
index.htm
default.css
index.htm
default.css
index.htm
marquee-alternate.png
marquee-scroll.png
marquee-slide.png
W3C-CR.css
default.css
index.htm
default.css
index.htm
index.htm
AlignIntro-1.gif
AlignIntro-2.gif
AlignIntroB-2FS.gif
AlignIntroB-3DH.gif
AlignIntroB-3RS.gif
AlignIntroB-4FS.gif
AlignIntroB-5.gif
AlignIntroB-5FS.gif
AlignmentPointsMixedScripts2.gif
AlignmentPointsMixedScriptsOnBaselines.gif
ArrowsInText.gif
Baselines-HorizAndVert-ApCountry.gif
Baselines-rev.gif
dc-accents.gif
dc-devanagari.gif
dc-ideo.gif
dc-lowercase.gif
dc-simple.gif
dc-symbols.gif
dc-upperq.gif
dc-variable.gif
default.css
index.htm
inline-layout.gif
default.css
index.htm
list-inout.gif
roman-4294967296.png
BottomCenterMarginBox.png
BottomLeftCornerBox.png
BottomLeftMarginBox.png
BottomRightCornerBox.png
BottomRightMarginBox.png
default.css
fit.png
header-ex-1.png
header-ex-2.png
header-ex-3.png
header-ex-4.png
header-ex-5.png
header-ex-6.png
index.htm
LeftMarginBoxes.png
PageBox.png
PageSheet.png
RightMarginBoxes.png
TopCenterMarginBox.png
TopLeftCornerBox.png
TopLeftMarginBox.png
TopRightCornerMarginBox.png
TopRightMarginBox.png
default.css
index.htm
default.css
index.htm
default.css
index.htm
default.css
index.htm
bopomofo.gif
default.css
fullwidth.gif
halfwidth.gif
index.htm
ra-c.gif
ra-c-h.gif
ra-c-rb.gif
ra-c-rb-h.gif
ra-dl.gif
ra-dl-rb.gif
ra-ds.gif
ra-ds-rb.gif
ra-l.gif
ra-le-l.gif
ra-le-r.gif
ra-l-rb.gif
ra-r.gif
ra-r-rb.gif
r-box-g.gif
r-box-h.gif
r-box-t.gif
rlh-a.gif
rlh-b.gif
ro-a.gif
ro-e.gif
ro-n.gif
ro-s.gif
ruby-univ.gif
shinkansen-bottom.gif
shinkansen-left.gif
shinkansen-right.gif
shinkansen-top.gif
default.css
first-letter.gif
first-letter2.gif
index.htm
initial-cap.png
W3C-PR.css
aural-box.png
default.css
index.htm
aapje.png
cutout.svg
diagram.png
footnotes.png
form.png
granite.png
index.htm
newspaper.png
overlap.png
table1.png
table2.png
table3.png
table4.png
table5.png
default.css
index.htm
TimingFunction.png
transition1.png
default.css
index.htm
pixel1.png
pixel2.png
default.css
horizontal.png
index.htm
tate-chu-yoko.png
vert-horiz-combination.png
vert-horiz-comparison.png
vertical-lr.png
vertical-rl.png
vert-latin-layouts.png
index.htm
default.css
index.htm
index.htm