CSS Template Layout is not only for big grids

W3C

Bert Bos | CSS Template Layout…

Cascading Style Sheets

Bert Bos (W3C)
XTech 2008
Dublin, Ireland, May 8, 2008

About CSS, W3C & me

W3C (the World Wide Web Consortium) exists since 1994 and is a consortium with some 425 members from industry and research, focused on creating technology and guidelines for the Web, on all devices and networks. Its director Tim Berners-Lee leads a team of some 70 people, located all over the world, who are responsible for the technical details as well as the overall architecture, and also for the process, including IPR policies.

W3C is the home of such technologies as HTML, XForms and XML (10 years old this year!).

CSS is W3C's main style sheet language (the other is XSL) and is one of the oldest of W3C's technologies. It was in 1996 only the second “W3C Recommendation,” the first being PNG. It is also one of the best known: an estimated 75 % of all HTML pages uses CSS, and CSS is also used with SVG, XHTML, MathML and other formats.

CSS level 2 is what is currently implemented in browsers and other software. A revision is under way (since a long time, but nearing completion) to fix some bugs and ambiguities.

Some software already implements parts of level 3, but level 3 contains rather more features than level 2 and it will take a few years before all specifications are ready. This talk is about one new module of CSS, the CSS Template Layout Module (formerly the Advanced Layout Module).

As for me, I work at the French site of W3C, in Sophia-Antipolis.

Part 1

Example: a large panel

Information board

Lorem ipsum dolor sit amet, consectetaur adipisicing.
Elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco Cak pwico siructiun ruos t harumd dereud facilis est er laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt. Sowios uf Zerm hawr. Whag schengos, uf efed, quiel ba rwivos. Unte af phen neige pheings atoot Prexs eis roxas eis ti Plokeing quert loppe eis yop prexs. Piy opher hawers, eit yaggles orn ti sumbloat alohe plok. Su havo loasor cakso tgu pwuructs tyu InfuBwain, ghu gill nug bo suloly sispunsiblo fuw cakiw salo anr ristwibutiun.
In culpa qui officia deserunt.
Like Greek to me, dereud facilis est er expedit distinct. Nam liber te conscient to factor tum poen legum odioque civiuda. Et tam neque pecun modut est neque nonor et imper ned libidig met, consectetur adipiscing elit, sed ut labore consectetur adipiscing elit, set eiusmod tempor et dolore At vver eos et accusam dignissum qui blandit est praesent luptatum delenit aigue excepteur sint occae. Et harumd dereud facilis est er expedit distinct. Nam libe soluta nobis eligent optio est congue nihil impedit doming id Lorem ipsum dolor sit amet, magna aliquam makes one wonder who would ever read this stuff? Bis nostrud exercitation ullam mmodo consequet.
Duis aute in voluptate velit esse cillum dolore eu fugiat nulla pariatur. At vver eos et accusam dignissum qui blandit est praesent luptatum delenit aigue excepteur sint occae. Et harumd dereud facilis est er expedit distinct. Hei muk neme eis loppe. Treas em wankeing ont sime ploked peish rof phen sumbloat syug si phat phey gavet peish ta paat ein pheeir sumbloats. Aslu unaffoctor gef cak siructiun gill bo cak spiarshoot.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.
Nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse molestaie cillum. Tia non ob ea soluad incommod quae egen ium improb fugiend.
1905 Officia deserunt mollit anim id est laborum Et harumd dereud facilis est er expedit distinct. Nam liber te conscient to factor tum poen legum odioque civiuda et tam. Neque pecun modut est neque nonor et imper ned libidig met, consectetur adipiscing elit, sed ut labore et dolore magna aliquam is nostrud exercitation ullam mmodo consequet.
1907 Duis aute in voluptate velit esse cillum dolore eu fugiat nulla pariatur. At vver eos et accusam dignissum qui blandit est praesent. Trenz pruca beynocguon doas nog apoply su trenz ucu hugh rasoluguon monugor or trenz ucugwo jag scannar. Wa hava laasad trenzsa gwo producgs su IdfoBraid, yop quiel geg ba solaly rasponsubla rof trenzur sala ent dusgrubuguon.
1913 Plloaso mako nuto uf cakso dodtos anr koop a cupy uf cak vux noaw yerw phuno. Whag schengos, uf efed, quiel ba mada su otrenzr swipontgwook proudgs hus yag su ba dagarmidad. Plasa maku noga wipont trenzsa schengos ent kaap zux copy.
1923 Wipont trenz kipg naar mixent phona. Cak pwico siructiun ruos nust apoply tyu cak UCU sisulutiun munityuw uw cak UCU-TGU jot scannow. Trens roxas eis ti Plokeing quert loppe eis yop prexs. Piy opher hawers, eit yaggles orn ti sumbloat alohe plok.
1953 Su havo loasor cakso tgu pwuructs tyu InfuBwain, ghu gill nug bo suloly sispunsiblo fuw cakiw salo anr ristwibutiun. Hei muk neme eis loppe. Treas em wankeing ont sime ploked peish rof phen sumbloat syug si phat phey gavet peish ta paat ein pheeir sumbloats. Aslu unaffoctor gef cak siructiun gill bo cak spiarshoot anet cak GurGanglo gur pwucossing pwutwam. Ghat dodtos, ig pany, gill bo maro tyu ucakw suftgasi pwuructs hod yot tyubo rotowminor. Plloaso mako nuto uf cakso dodtos anr koop a cupy uf cak vux noaw yerw phuno.
Pwicos asi sirucor. Thas sirutciun applios tyu thuso.
Itoms ghuso pwicos gosi sirucor mixent ples cak ontisi.
 
Nam libe soluta nobis eligent optio est congue nihil impedit doming id Lorem ipsum dolor.
Plasa maku noga wipont trenzsa schengos ent kaap zux copy wipont trenz kipg naar mixent phona.
Anet cak GurGanglo gur pwucossing pwutwam. Ghat dodtos, ig pany, gill bo maro tyu ucakw suftgasi.
Sit amet, consectetur adipiscing elit, set eiusmod tempor incidunt et Su havo loasor cakso tgu pwuructs labore et dolore magna aliqua.
 
Ffoctivo immoriatoly, hawrgasi
Eit sakem eit vory gast te Plok peish ba useing phen roxas. Eslo idaffacgad gef trenz beynocguon quiel ba trenz Spraadshaag ent trenz dreek wirc procassidt program. Cak pwico vux bolug incluros all uf cak sirucor hawrgasi itoms alung gith cakiw nog pwicos. Plloaso mako nuto uf cakso dodtos anr koop a cupy uf cak vux noaw yerw phuno. Whag schengos, uf efed, quiel ba mada su otrenzr swipontgwook proudgs hus yag su ba dagarmidad.
 

Despite the title of this talk, let's start with a big grid.

The above is a recreation of a display panel that I saw in a museum last week and that I decided to use as an example, because it shows a very wide “screen” (optimal use of large screens is one of the goals of the Template Layout module) and needs no other new modules (such as for rotation or columns).

The (low-quality) photo at the bottom shows the original panel, the rest is a simulation (using HTML tables and nonsense text) of the layout of the photo.

The Template Layout module is based on the concept of layout grids (well-known to graphic designers), with some extensions to deal with dynamic media: variable screen sizes, scroll bars, etc. The first step in translating this design to CSS is therefore to recognize the (invisible) grid. The next slide shows that grid.

Information board – grid

The minimum number of grid lines we need to position all text and pictures seems to be as shown above: eight columns and seven rows.

Maybe the designer used more, but I don't know how to ask him. Also the photo is of such low quality, that I'm not sure of the exact sizes of each row and column.

Let's start by giving names to the various part of the grid, so that we can describe it more precisely and have some handles for positioning the content later.

Information board – template 1

"a b b c d d e f"
"a b b g h h e f"
"a i . g h h e f"
"j j k k h h l f"
"j j m m h h l f"
"j j n n n . o f"
"p p n n n . o f"

… but column widths not equal

The proposed method for describing grids in CSS is to use letters for the “slots” formed by the grid lines. The letters are arbitrary, you can also use Greek or Chinese or anything else (but not digits or spaces, they have other functions).

When slots span across grid lines, that is indicated by repeating the letter. E.g., the top left slot (a) is one column wide and three rows high. There are thus three a's in the grid.

The resulting matrix of letters is called a “template” in CSS.

The dot (.) has a special function: if we know for sure that a certain slot will remain empty, we don't have to give it a name and we put a dot instead.

This template translates the structure of the grid, but we're still missing information about the (relative) size of the rows and columns. The next slide shows one way to fix that.

Information board – template 3

"aabbbbcccdddddeeefff"
"aabbbbggghhhhheeefff"
"aaiii.ggghhhhheeefff"
"jjjjjkkkkhhhhhlllfff"
"jjjjjmmmmhhhhhlllfff"
"jjjjjnnnnnnnn.ooofff"
"pppppnnnnnnnn.ooofff"

The default rule for grid templates in the proposed CSS module is that all columns have the same width and all rows are no higher than needed for their contents. This is similar to how tables work in the 'fixed' table layout.

Most designers make grids that consist of equal-sized columns or of columns that are multiples of other columns, so this rule makes sense. In this example I assume that the designer also started with a grid of equal columns. In that case it seems (based on the bad photo) that there are actually 20 grid columns that are combined into slots of between one and eight columns.

The slide shows the panel with the imaginary 20 grid columns and its representation in CSS.

Information board – template (alt.)

Alternative (if line length important):

"a    b    b    c    d    d    e    f"
"a    b    b    g    h    h    e    f"
"a    i    .    g    h    h    e    f"
"j    j    k    k    h    h    l    f"
"j    j    m    m    h    h    l    f"
"j    j    n    n    n    .    o    f"
"p    p    n    n    n    .    o    f"
12em 18em 6em  18em 24em 6em  18em 18em

The previous slide defined the grid template without specifying any actual length. The grid is thus relative to the size of something else, usually the window's width.

Sometimes we don't want columns that are of relative size, but we want all or some columns to have a specific, fixed width.

This slide shows that other extreme: all columns have a fixed width, independent of the size of the containing element or window.

The methods can be combined: some flexible columns and some fixed ones. (There is even an ongoing investigation if we need different levels of flexibility: some columns may have a maximum size, or become flexible only when all other columns have no more flexibility. The use case is dialog boxes in graphical user interfaces. But the current module has only binary flexibility. Other algorithms may be added later if the need is proved.)

Information board – CSS

body { 
  display:
    "aabbbbcccdddddeeefff"
    "aabbbbggghhhhheeefff"
    "aaiii.ggghhhhheeefff"
    "jjjjjkkkkhhhhhlllfff"
    "jjjjjmmmmhhhhhlllfff"
    "jjjjjnnnnnnnn.ooofff"
    "pppppnnnnnnnn.ooofff"
} 
...

The previous slides showed the template, but not yet in a CSS style rule. To attach a template to an element, the template has to be set on the 'display' property.

By default, an element that is a template is block-level, but it can also be inline (similar to an inline-block).

A template element acts as a template for its descendant elements, which are each positioned into a slot of the template. Multiple elements can be put in the same slot.

The next slide shows how that positioning works.

Information board – CSS

#photo1 { position: a }
#history { position: b }
#photo2 { position: c }
#timeline { position: f }
...

(There is also a default position)

To position an element in a slot of a grid, it is enough to set the element's 'position' property to the name of the slot. This is similar to absolute positioning, except that there is no need for the 'top' and 'left' properties, because the coordinates are implicit in the grid.

Multiple elements positioned to the same slot are laid out as block elements one after the other, as if they were sibling block elements and the slot was their parent.

Children are positioned along with their parent, unless they have a similar 'position' of their own. (I.e., as long as their 'position' is either 'static' or 'relative'.)

The anonymous content of a template element as well as any non-positioned children are placed in the default slot of the grid. If there is a slot called '@', that is the default, otherwise it is the first slot on the top left (skipping empty, dot slots).

Part 2

Example: a medium size screen

Medium-size example

(Example: a page whose body can
        be seen as a grid with 4 columns and 3 rows)
(image © Jina Bolton)

Expressing it in CSS:

Let's do the same exercise again, with a different design. This example is due to Jina Bolton and can be found in her Future of Web Design 2007 talk on Creating Sexy Style Sheets (used with permission).

The live demo (at the end of this talk) will use this same example.

As we have seen, to express a grid in CSS, we need a notation in the form of text. Grids are two-dimensional and visual, but we need to describe them linearly. And grids also carry information about their function: some parts of the grid are reserved for images, others for text and others for additional information.

Thus we need to describe where the lines of the grid are and find ways to identify the areas in the grid. Then we need to associate elements in the document with positions in the grid.

Because we are dealing, usually, with variable window sizes, the CSS version of the grid must also define how it reacts to changes in size (something that is not necessary in traditional, paper-based design).

Template layout – describe

(Example:
        the same page with the implied grid made visible compared to the page itself)
(image © Jina Bolton)

Describe the grid & name the parts:

… let's give them names

The image shows the same page as on the previous slide, but overlaid with the grid lines that the designer used for the layout. The letters indicate distinct areas in the grid. Note that the a and e areas are double the width of the other areas.

Template layout – describe (cont'd)

(Example: the same page with the
        implied grid made visible)
(image © Jina Bolton)

… and in CSS:

display:
    "a a c d"
    "e e g g"
    "i j k l"

We've taken the names (letters) of the areas in the grid and simply written them down as three sequences of four letters, corresponding to the three rows of four columns.

Nothing else is needed in this example, because the columns are all the same width and thus their size is fully determined by the fact that they are four.

If the columns of the grid are not the same width, especially if some are flexible and others are fixed, that information has to be added at the end, after the last line.

Template layout – new design

New design:

(Example: the same page with content arranged
        differently) display:
"ppqq"
"rstu"
"vwxy"

One goal of the Template Layout module is to make it easy to change the design, and especially to make it easy to create multiple layouts for the same page, corresponding to different screen sizes and kinds of devices. (That requires the Media Queries module.) We'll show this in the demo later on as well.

This alternate template has double-width slots on the first row, but not on the second.

The elements are also positioned in a different order. The next slide will show how elements are associated with slots in the template.

This shows again how the grid is used as a template (hence the name of the module that describes these features).

Template layout – bind

CSS
        Template Layout Module

Bind elements to locations

#what { position: e }
#maki { position: a }
#sashimi { position: i }
...

Grid positioning is a form of positioning, except that we don't need the 'top' and 'left' properties to set the coordinates of the element. Instead, we position an element into a named slot in the template.

Part 3

Example: a math formula

Math example

8.44x + .55y = −0.0
03.1x − 0.7y = −1.1

The previous two examples showed relatively large grids, covering a good part of the page, if not all of it. But grids can also be used on a more local scale, such as in this example, to align the parts of a mathematical formula.

Template layout is not enough to replace a real mathematical typesetting system. To render all of MathML with the quality of a professional text book needs other extensions to CSS, or a dedicated math typesetter. But CSS can make acceptable displays in some cases.

To make the formula show on this slide, without the benefit of a dedicated math system and without grids, required some ugly tricks: this is not good mark-up for math in HTML!

But let's see, on the next slide, how the formula looks in correct mark-up, MathML, and how a grid template can render that without changes in the mark-up.

Math example – source

8.44x + .55y = −0.0
03.1x − 0.7y = −1.1

<mtable
    groupalign="{right left right left right}" >
  <mtr>
    <mtd>
      <mrow>
	<mrow>
	  <mrow>
	    <maligngroup/>
	    <mn> 8.44 </mn>
	    <mo> &it; </mo>
	    <mi> x </mi>
	  </mrow>
	  <maligngroup/>
	  <mo> + </mo>
	  <mrow>
	    <maligngroup/>
	    <mn> 55 </mn>
	    <mo> &it; </mo>
	    <mi> y </mi>
	  </mrow>
	</mrow>
      <maligngroup/>
      <mo> = </mo>
      <maligngroup/>
      <mn> 0 </mn>
    </mrow>
    </mtd>
  </mtr>
  <mtr>
    <mtd>
      <mrow>
	<mrow>
	  <mrow>
	    <maligngroup/>
	    <mn> 3.1 </mn>
	    <mo> &it; </mo>
	    <mi> x </mi>
	  </mrow>
	  <maligngroup/>
	  <mo> - </mo>
	  <mrow>
	    <maligngroup/>
	    <mn> 0.7 </mn>
	    <mo> &it; </mo>
	    <maligngroup/>
	    <mi> y </mi>
	  </mrow>
	</mrow>
	<maligngroup/>
	<mo> = </mo>
	<maligngroup/>
	<mrow>
	  <mo> - </mo>
	  <mn> 1.1 </mn>
	</mrow>
      </mrow>
    </mtd>
  </mtr>
</mtable>

MathML is a bit verbose, because it is very explicit about the hierarchical relations between the operators and operands in the formula. That hierarchy is shown in much more subtle ways in the human-readable form of the finished formula.

This talk is not about MathML and I won't explain the source code that is shown above, but we need to understand the structure enough to be able to attach CSS properties to the right parts of the formula. The next slide shows the main structure graphically.

Math example – structure

8.44x + .55y = −0.0
03.1x0.7y = −1.1

┌ mrow 8.44x
┌ mrow +
└ mrow 55y
┌ mtr ─ mtd ─ mrow =
0
mtable ┌ mrow 3.1x
┌ mrow
└ mrow 0.7y
└ mtr ─ mtd ─ mrow =
−1.1

As recommended by the MathML specification, this formula has one mrow element per operator. The operators are +, -, = and “invisible times”: there is an implied multiplication between the 8.44 and the x.

Our task is to align the operators, despite the different lengths of the operands.

Math example – template

8.44x + .55y = −0.0
03.1x − 0.7y = −1.1

mtable { display:
  "a b c d e"
  "f g h i j"
}

As in the previous examples, we start by defining our grid. In this case it seems reasonable to create five columns, because each line has three operands and two operators.

Math example – width

8.44x + .55y = −0.0
03.1x − 0.7y = −1.1

mtable { display:
  "a b c d e"
  "f g h i j"
  fit-content fit-content fit-content
  fit-content fit-content
}

In this case, the columns aren't all the same width, and they aren't a fixed size either, but they are the size of the content.

A new keyword, 'fit-content' (which will also be available for the 'width' property on arbitrary elements in CSS level 3), indicates that the column has to be as wide as needed for its content. (This is again similar to tables, in this case to the automatic table layout algorithm.)

Clearly, computing the size of the grid in this case is a bit more work than in the previous examples, where the size was known (actually not always, but usually) before the content was put in the slots. But this is no different than for tables.

Math example – space

8.44x_+_.55y_=_−0.0
03.1x__0.7y_=_−1.1

mtable { display:
  "a . b . c . d . e"
  "f . g . h . i . j"
  fit-content 0.3em fit-content
  0.3em fit-content 0.3em
  fit-content 0.3em fit-content
}

Math typography requires different amounts of space in different places. In this case there is space on the sides of the operators. We can of course set appropriate 'margin' properties, but in this case I've chosen to put the space in the template, with the help of empty (.) slots.

As the numbers under the template show, these empty slots are a fixed 0.3em wide.

Math example – bind

8.44x + .55y = −0.0
03.1x − 0.7y = −1.1

mtr:nth-child(1) mrow > mrow > mrow:nth-child(1) {
  position: a }
mtr:nth-child(1) mrow > mrow > mo {
  position: b }
mtr:nth-child(1) mrow > mrow > mrow:nth-child(3) {
  position: c }
mtr:nth-child(1) mrow > mo {
  position: d }
mtr:nth-child(1) mrow > mn {
  position: e }

I didn't put IDs or classes on the various elements, and that means the selectors are a bit more complex than the ones in the previous examples. Experience shows that selectors for MathML are typically longer than selectors for HTML. That probably has to do with the fact that a relatively small number of element names (mrow!) is used very often and that formulas are typically deeply nested.

But this talk is not about selectors, so let's not dwell on them. The above code shows the rules to position the elements of the first row. The second row is similar.

Part 4

Page templates

Page templates

Grids can not only be attached to elements, but also to pages, at least in paged media (such as print and projection). The template for the grid is put inside an @page rule.

An element with a 'position' (and no template ancestor) will be put in the named slot on the current page. If that slot is full, a new page will be created with the same template and the contents will go in the same slot on that next page (at least if 'overflow' is 'auto' or 'scroll').

There is maybe a need for something to indicate that the text continues on the next page (“continued on next page”) but there is currently no proposal for such a feature.

Demo

The prototype implementation uses JavaScript to transform a document and its style sheet to something that simulates the intended layout. It can't do all the features of the module, but it is enough for some common cases.

Because of limitations of the DOM, it also requires a slightly different syntax. The 'display' property cannot be used and must be called 'display-model' instead; and similarly 'position' must be called 'situated'. The string syntax also includes a comma, to make parsing easier.

The first demo shows the earlier “sushi” example by Jina Bolton actually running in a browser. By changing the template, the various elements can change position, independent of their original order.

The second demo shows a recreation of the cover of a famous book on typography by Jan Tschigold. Once the template has been created, nothing stops me from using it for the cover of my own book… apart from copyright, that is.

Conclusion

Demand:

Supply:

The Template Layout module is meant to help make optimal use of available (horizontal) space, because CSS level 2 is mostly designed for single-column layouts.

In combination with Media Queries, the grid templates make it easy to provide several layouts of the same page, for different screen sizes and devices.

Graphic designers are trained to use grids and one goal of the Template Layout module is to make the translation of the design grid to CSS easier.

The module thus provides the best features of table layout (automatic alignment of objects to one another, both vertically and horizontally) and of absolute positioning (making the 2D layout independent of the linear order of elements in the document).

It also provides templates for printed pages. (In practice, printed pages will often also use the multicolumn module, another new module of CSS level 3.)

More info

http://www.w3.org/Talks/2008/0508-CSS-Dublin/

W3C talks can always be found from the W3C Talks page.

Information about other modules of CSS level 3 is available on the CSS road map page.