<<

Constraint Cascading Style Sheets for the Web

Technical Report UW CSE 99-05-01 7 May 1999, Revised 3 August 1999

Greg J. Badros Alan Borning Dept. of Computer Science and Engineering Dept. of Computer Science and Engineering University of Washington, Box 352350 University of Washington, Box 352350 Seattle, WA 98195-2350, USA Seattle, WA 98195-2350, USA [email protected] [email protected]

Kim Marriott Peter Stuckey School of Computer Science and Software Engineering Dept. of Computer Science and Software Engineering Monash University University of Melbourne Clayton, Victoria 3168, Australia Parkville, Victoria 3052, Australia [email protected] [email protected]

ABSTRACT displayed. Thus, there is a clean separation between doc- Cascading Style Sheets have recently been introduced by the ument structure and appearance, yet the designer has con- W3C as a mechanism for controlling the appearance of HTML siderable control over the final appearance of the document. documents. In this paper, we demonstrate how constraints W3C has introduced Cascading Style Sheets,firstCSS1.0 provide a powerful unifying formalism for declaratively un- and now CSS 2.0, for use with HTML documents. derstanding and specifying style sheets for web documents. With constraints we can naturally and declaratively specify Despite the clear benefits of cascading style sheets, there are complex behaviour such as inheritance of properties and cas- several areas in which the CSS 2.0 standard can be improved. cading of conflicting style rules. We give a detailed descrip- The designer lacks control over the document’s appearance tion of a constraint-based style sheet model, CCSS, which is • in environments different from her own. For example, if compatible with virtually all of the CSS 2.0 specification. It the document is displayed on a monochrome display, if allows more flexible specification of layout, and also allows fonts are not available, or if the browser window is sized the designer to provide multiple layouts that better meet the differently, then the document’s appearance will often be desires of the user and environmental restrictions. We also less than satisfactory. describe a prototype extension of the Amaya browser that CSS 2.0 has seemingly ad hoc restrictions on layout spec- demonstrates the feasibility of CCSS. • ification. For example, a document element’s appearance can often be specified relative to the parent of the element, KEYWORDS: Constraints, HTML, style sheets, CSS, Cas- but generally not relative to other elements in the docu- cading Style Sheets, CCSS, , page layout, ment. Cassowary The CSS 2.0 specification is complex and sometimes vague. • It relies on procedural descriptions to understand the effect INTRODUCTION of complex language features, such as table layout. This Since the inception of the Web there has been tension be- makes it difficult to understand how features interact. tween the “structuralists” and the “designers.” On one hand, Browser support for CSS 2.0 is still limited. We conjecture structuralists believe that a Web document should consist • that this is due in part to the complexity of the specifica- only of the content itself and tags indicating the logical struc- tion, but also because the specification does not suggest a ture of the document, with the browser free to determine the unifying implementation mechanism. document’s appearance. On the other hand, designers (un- derstandably) want to specify the exact appearance of the We argue that constraint-based layout provides a solution to document rather than leaving it to the browser. all of these issues, because constraints can be used to specify declaratively the desired layout of a web document. They With the recent championing of style sheets by the World- allow partial specification of the layout, which can be com- Wide-Web Consortium (W3C), this debate has resulted in a bined with other partial specifications in a predictable way. compromise. The web document proper should contain the They also provide a uniform mechanism for understanding content and structural tags, together with a link to one or layout and cascading. Finally, constraint solving technology more style sheets that determine how the document will be provides a unifying implementation technique.

1 We describe a constraint-based extension to CSS 2.0, called Simple Example Constraint Cascading Style Sheets (CCSS). The extension css" straints to the style sheet to control features such as object TYPE="text/css"> placement, and finite-domain constraints to control features such as font properties. Constraints may be given a strength,

Famous Quotes

reflecting their relative importance. They may be used in

At a party at Blenheim Palace, style rules in which case rewritings of the constraint are cre- Lady Astor said to ated for each applicable element. Multiple style sheets are Winston Churchill: available for the same media type (e.g., paper vs. screen) with

preconditions on the style sheets determining which are ap- If I were married to you, I’d put poison in your coffee. And he responded: propriate for a particular environment and user requirements.
Our main technical contributions are: If you were my wife, I’d drink it.
A demonstration that constraints provide a powerful uni-
• fying formalism for declaratively understanding and spec-

ifying CSS 2.0. A detailed description of a constraint-based style sheet • model, CCSS, which is compatible with virtually all of the CSS 2.0 specification. CCSS is a true extension of Figure 1: Example HTML Document CSS 2.0. It allows more flexible specification of layout, and also allows the designer to provide multiple layouts that better meet the desires of the user and environmental be either absolute or relative to the parent element’s value. restrictions. For instance, the style sheet A prototype extension of the Amaya browser that demon- • strates the feasibility of CCSS. The prototype makes use H1 { font-size: 13pt } of the sophisticated constraint solving algorithm Casso- P { font-size: 11pt } wary [4] and a simple one-way binary acyclic finite-domain BLOCKQUOTE { font-size: 90% } solver based on BAFSS [12]. Figure 2: simple.css BACKGROUND Cascading Style Sheets (CSS 1.0 in 1997 and CSS 2.0 in has three rules. The first uses the selector H1 to indicate that 1998) were introduced by the W3C in association with the it applies to all elements with tag H1 and specifies that those HTML 4.0 standard. In this section we review relevant as- first-level headings should be displayed using a 13 pt font. pects of CSS 2.0 [6] and HTML 4.0 [9]. The second rule specifies that paragraph elements should use an 11 pt font. The third rule specifies the appearance of CSS 2.0 and HTML 4.0 provide a comprehensive set of text in a BLOCKQUOTE, specifying that the font-size should “style” properties for each type of HTML tag. By setting be 90% of that of the surrounding element. the value of these properties the document author can control how the browser will display each element. Broadly speak- We can use this style sheet to specify the appearance of the ing, properties either specify how to position the element HTML document shown in Figure 1. Notice the link to the relative to other elements, e.g. text-indent, margin,or style sheet and that we have included an ID attribute for all float, or how to display the element itself, e.g. font-size elements since we will refer to them later.1 or color. Selectors come in three main flavors: type, attribute,and Although the author can directly annotate elements in the contextual. These may be combined to give more complex document with style properties, CSS encourages the author selectors. We have already seen examples of a type selector to place this information in a separate style sheet and then in which the document elements are selected by giving the link or import that file. Thus, the same document may be “type” of their tag. For example, the type-selector H1 refers displayed using different style sheets and the same style sheet to all first-level heading elements. The wildcard type, “*”, may be used for multiple documents, easing maintenance of matches all tags. a uniform look for a web site. Attribute selectors choose elements based on the values of A style sheet consists of rules.Arulehasaselector that two attributes that each element in the document tree may specifies the document elements to which the rule applies, 1Marking all elements with ID attributes defeats the modularity and re- and declarations that specify the stylistic effect of the rule. use benefits of CSS; we over-use ID tags here strictly as an aid to discussing The declaration is a set of property/value pairs. Values may our examples.

2 HTML Table Example TITLE LINK H1 P

BLOCKQUOTE BLOCKQUOTE optionally provide: CLASS and ID. Multiple elements may specify the same CLASS value, while the ID value should be unique. Selection based on the CLASS and ID attributes provides con- siderable power. By using CLASS attributes and selectors, the
Figure 3: Document tree for the HTML of Figure 1.
Text1Text2 Text3
author can categorize various document elements into groups and then apply different formatting to each of the groups. Similarly, by using ID attributes and selectors, the author can single out document elements for special formatting and then Figure 4: Example HTML Document refer to them from the style sheet. Elements with a specific class value are selected using the syntax “.class”, while in- parent tables, respectively. (Note the use of the class selector stance ids are selected with “#id”. “.” syntax). Contextual selectors allow the author to take into account .medcol { width: 30% } where the element occurs in the document, i.e. its . .thincol { width: 20% } They are based on the document’s document tree, which cap- tures the recursive structure of the tagged elements. A con- Figure 5: table.css text selector allows selection based on the element’s ances- tors in the document tree. One of the key features of CSS is that it allows multiple style For instance, the preceding document has the document tree sheets for the same document. Thus a document might be shown in Figure 3. If we want to ensure the innermost block displayed in the context of the author’s special style sheet for quote does not have its size reduced relative to its parent, we that document, a default company style sheet, the user’s style could use sheet and the browser’s default style sheet. This is handled in CSS by cascading the style sheets, permitting each of the BLOCKQUOTE BLOCKQUOTE { font-size: 100% } sheets to affect the final rendering. Less generally, we could individually override the font size Cascading, inheritance, and multiple style sheet rules match- for the second BLOCKQUOTE by using a rule with an ID se- ing the same element may mean that there are conflicts among lector: the rules as to what value a particular style property for that element should take. The exact details of which value is cho- #Q2 { font-size: 100% } sen are complex. Within the same style sheet, inheritance is weakest, and rules with more specific selectors are preferred Many style properties are inherited by default from the el- to those with less specific selectors. For instance, each of the ement’s parent in the document tree. Generally speaking, rules properties that control the appearance of the element itself, such as font-size, are inherited, while those that control #Q2 { font-size: 100% } BLOCKQUOTE BLOCKQUOTE { font-size: 100% } its positioning are not. is more specific than As another example, consider the HTML document shown in Figure 4. We can use a style sheet to control the width of the BLOCKQUOTE { font-size: 90% } columns in the table. For example, table.css (Figure 5) contains rules specifying that the elements of the classes Among style sheets, the values set by the designer are pre- medcol and thincol have widths 30% and 20% of their ferred to those of the user and browser, and for otherwise

3 equal conflicting rules, those in a style sheet that is imported conflict. To allow for this we use the constraint hierarchy or linked first have priority over those subsequently imported formalism [3]. A constraint hierarchy consists of a collec- or linked. However, a style sheet author may also annotate tion of constraints, each labeled with a strength. There is a rules with the strength !important, which will override this distinguished strength labeled REQUIRED: such constraints behavior. In CSS 2.0, for rules designated with strength !im- must be satisfied. The other strengths denote preferences. portant, user-specified rules take priority over designer- There can be an arbitrary number of such strengths, and con- specified rules.2 straints with stronger strengths are satisfied in preference to ones with weaker strengths. Given a system of constraints, Despite its power, CSS 2.0 still has a number of limitations. the constraint solver must find a solution to the variables that One limitation is that a style property may only be relative to satisfies the required constraints exactly, and that satisfies the the element’s parent, not to other elements in the document. preferred constraints as well as possible, giving priority to This can result in clumsy specifications, and makes some rea- those more strongly preferred. The choice of solution de- sonable layout constraints impossible to express. For exam- pends on the comparator function used to measure how well ple, it is not possible to require that all tables in a document a constraint is satisfied. In our examples we shall assume the have the same width, and that this should be the smallest weighted-sum-better comparator that sums the errors in sat- width that allows all tables to have reasonable layout. With isfying each of the constraints, weighting each error by the CSS 2.0, one can only give the tables the same fixed size or strength of that constraint. By using an appropriate set of the same fixed percentage width of their parent element. strength labels we can model the behavior of CSS 2.0.

The other main limitation is that it is difficult for the designer A Constraint View of CSS 2.0 to write style sheets that degrade gracefully in the presence Hierarchical constraints provide a simple, unifying way of of unexpected browser and user limitations and desires. For understanding much of the CSS 2.0 specification. This view- instance, the author has little control over what happens if point also suggests that constraint solvers provide a natu- the desired fonts sizes are not available. Consider the style ral implementation technique. Each style property and the sheet simple.css again. Imagine that only 10 pt, 12 pt, and placement of each element in the document can be mod- 14 pt fonts are available. The browser is free to use 12 pt and eled by a variable. Constraints on these variables arise from 10 pt for headings and paragraphs respectively, or 14 pt and browser capabilities, default layout behavior arising from the 12 pt, or even 12 pt and 12 pt. Part of the problem is that type of the element, from the document tree structure, and rules always give definite values to style properties. When from the application of style rules. The final appearance of different style sheets are combined only one rule can be used the document is determined by finding a solution to these to compute the value. Thus a rule is either on or off, leading constraints. to discontinuous behavior when style sheets from the author and user are combined. For instance, a sight-impaired user The first aspect of CSS 2.0 we consider is the placement of might specify that all font sizes must be greater than 11 pt. the document elements (i.e., page layout). This can be mod- However, if the designer has chosen sufficiently large fonts, eled using linear arithmetic constraints. To illustrate this, we the user wishes to use the designer’s size. This is impossible examine table layout—one of the most complex parts of CSS in CSS 2.0. 2.0. The key difficulty in table layout is that it involves infor- mation flowing bottom-up (e.g. from elements to columns) CONSTRAINT CASCADING STYLE SHEETS and top-down (e.g. from table to columns). The CSS 2.0 Our solution to these problems is to use constraints for spec- specification is procedural in nature, detailing how this oc- ifying layout. A constraint is simply a statement of a rela- curs. By using constraints, we can declaratively specify what tion (in the mathematical sense) that we would like to have the browser should do, rather than how to do it. Furthermore, hold. Constraints have been used for many years in inter- the constraint viewpoint allows a modular specification. For active graphical applications for such things as specifying example, to understand how a complex nested table should window and page layout. They allow the designer to specify be laid out, we simply collect the constraints for each com- what are the desired properties of the system, rather than how ponent, and the solution to these is the answer. With a pro- these properties are to be maintained. The major advantage cedural specification it is much harder to understand such of using constraints is that they allow partial specification of interaction. the layout, which can be combined with other partial spec- ifications in a predictable way. In this section, we describe Consider the style sheet table.css (Figure 5) and the as- our constraint-based extension to CSS 2.0, called Constraint sociated HTML document (Figure 4). The associated layout Cascading Style Sheets (CCSS). constraints are shown in Figure 6. The notation #id[prop] refers to the value of the property prop for the presentation One complication in the use of constraints is that they may element corresponding to the document element with ID id.3 Since we are dealing with a table, the system automatically 2This seemingly-inconsistent relative ordering of the !important preferences was changed from CSS 1.0 to guarantee that the user has ulti- 3We use associative array-like syntax for referring to properties of el- mate control over the appearance of a document. ements to avoid the confusion that the alternative “.selector” form would

4 (1) #t[width]=#c1[width]+ (1) #h[font-size] 9,10, 12, 16, 36, 72 REQUIRED ∈{ } #c2[width]+#c3[width] REQUIRED (2) #p[font-size] 9,10, 12, 16, 36, 72 REQUIRED ∈{ } (2) #c1[width] width(“Text1”) REQUIRED (3) #q1[font-size] 9,10, 12, 16, 36, 72 REQUIRED ≥ ∈{ } (3) #c2[width] width(“Text2”) REQUIRED (4) #q2[font-size] 9,10, 12, 16, 36, 72 REQUIRED ≥ ∈{ } (4) #c3[width] width(“Text3”) REQUIRED (5) #h[font-size]=13 DESIGNER ≥ (5) #c3[width] #i2[width] REQUIRED (6) #p[font-size]=11 DESIGNER ≥ (6) #c1[width]+#c2[width] #i1[width] REQUIRED (7) #q1[font-size]=0.9 #p[font-size] DESIGNER ≥ ∗ (7) #t[width]=0 WEAK (8) #q2[font-size]=0.9 #q1[font-size] DESIGNER ∗ (8) #c1[width]=0.3 #t[width] DESIGNER ∗ (9) #c3[width]=0.2 #t[width] DESIGNER Figure 7: Example finite domain constraints ∗ Figure 6: Example layout constraints #h[font-size]=13 DESIGNER,0,0,1 h i #p[font-size]=11 DESIGNER,0,0,1 h i creates a constraint (1) relating the column widths and table #q1[font-size]=0.9 #p[font-size] DESIGNER,0,0,1 ∗ h i width.4 Similarly, there are automatically created constraints #q2[font-size]=0.9 #q1[font-size] DESIGNER,0,0,1 ∗ h i (2-6) that each column is wide enough to hold its content, and #q2[font-size]=1.0 #q1[font-size] DESIGNER,0,0,2 ∗ h i (7) that the table has minimal width. Constraints (8) and (9) are generated from the style sheet. Notice the different con- Figure 8: Example of overlapping rules straint strengths: from weakest to strongest they are WEAK, DESIGNER and REQUIRED.SinceREQUIRED is stronger Both of the preceding examples have carefully avoided one than DESIGNER, the column will always be big enough to of the most complex parts of the CSS 2.0 specification: what hold its contents. The WEAK constraint #t[width] = 0 to do when multiple rules assign conflicting values to an el- cannot be satisfied exactly; the effect of minimizing its er- ement’s style property. As discussed earlier, there are two ror will be to minimize the width of the table, but not at the main aspects to this: cascading several style sheets, and con- expense of any of the other constraints. flicting rules within the same style sheet. These constraints provide a declarative specification of what We can model both aspects by means of hierarchical con- the browser should do. This approach also suggests an im- straints. To do so we need to refine the constraint strengths plementation strategy: to lay out the table, we simply use we have been using. Apart from REQUIRED, each strength is a linear arithmetic constraint solver to find a solution to the a lexicographically-ordered tuple constraints. The solver implicitly takes care of the flow of in- formation in both directions, from the fixed widths of the im- cs, i, , t . h i ages upward, and from the fixed width of the browser frame downward. The first component in the tuple, cs,istheconstraint im- portance and captures the author-suggested strength of the Linear arithmetic constraints are not the only type of con- constraint and its position in the cascade. The constraint straints implicit in the CSS 2.0 specification. There are also importance is one of WEAK, BROWSER, USER, DESIGNER, constraints over properties that can take only a finite num- DESIGNER-IMPORTANT,orUSER-IMPORTANT (ordered from ber of different values, including font size, font type, font weakest to strongest). The importance WEAK is used for au- weight, and color. Such constraints are called finite domain tomatically generated constraints only. The last three com- constraints and have been widely studied by the constraint ponents in the tuple capture the specificity of the rule that programming community [14]. Typically, they consist of a generated the constraint: i is the number of ID attributes, c domain constraint for each variable giving the set of values is the number of CLASS attributes, and t is the number of tag the variable can take (e.g., the set of font sizes available) and names in the rule (i.e., the depth of the contextual selection). required arithmetic constraints over the variables. As an example, consider the constraints arising from the doc- As an example, consider the constraints arising from the doc- ument in Figure 1 with the style sheet ument in Figure 1 and style sheet simple.css (Figure 2). The corresponding constraints are shown in Figure 7. The H1 { font-size: 13pt } domain constraints (1-4) reflect the browser’s available fonts. P { font-size: 11pt } BLOCKQUOTE { font-size: 90% } The remaining constraints result from the style sheet rules. BLOCKQUOTE BLOCKQUOTE { font-size: 100% } Note that the third rule generates two constraints (7) and (8), one for each block quote element. The constraints and their strengths for those directly gener- ated from the style sheet rules are shown in Figure 8. Be- cause due to CSS’s pre-existing use of “.” as a class-name prefix in selectors of rules. cause of its greater weight, the last constraint listed will 4For simplicity, we ignore margins, borders and padding in this example. dominate the second to last one, giving rise to the expected

5 that overcome the expressiveness limitations of CSS 2.0 dis- BODY[font-size]=12 BROWSER,0,0,0 h i cussed previously. We call this extension CCSS—Constraint #h[font-size]=BODY[font-size] WEAK,0,0,0 h i Cascading Style Sheets. #p[font-size]=BODY[font-size] WEAK,0,0,0 h i #q1[font-size]=#p[font-size] WEAK,0,0,0 h i As the above examples indicate, virtually all author and user #q2[font-size]=#q1[font-size] WEAK,0,0,0 h i constraints generated from CSS 2.0 either constrain a style #q1[font-size]=8 DESIGNER,0,0,1 h i property to take a fixed value, or relate it to the parent’s #q2[font-size]=8 DESIGNER,0,0,1 h i style property value. One natural generalization is to allow more general constraints such as inequalities. Another natu- Figure 9: Example of inheritance rules ral generalization is to allow the constraint to refer to other variables—both variables corresponding to non-parent ele- behavior—that the longer contextual selection of a block- ments and to “global” variables. quote within a blockquote will govern the appearance of In CCSS, we allow constraints in the declaration of a style those nested blockquotes. sheet rule. The CSS-style attribute:value pair is re- The remaining issue we must deal with is inheritance of style interpreted in this context as the constraint attribute = value. We prepend all constraint rules with the constraint properties such as font size, and the expression of this inher- pseudo-property so that CCSS is backwards compatible with itance within our constraint formalism. For each inherited browsers supporting only CSS. In a style sheet rule, the con- property, we need to automatically create an appropriate con- straint can refer to attributes of parent and left-sibling. straint between each element and its parent. At first glance, For example: these should simply be WEAK equality constraints. Unfor- tunately, this does not model the inherent directionality of P { constraint: inheritance. font-size <= (parent[parent])[font-size] + 2 } For instance, imagine displaying the document in Figure 1 with the style sheet is a rule that applies constraints that relate the font-size of a paragraph element to the font-size of its grandparent element. BLOCKQUOTE { font-size: 8pt } CCSS style sheets also allow the author to introduce global constrainable variables using a new @variable directive. where the default font size is 12 pt. The scheme outlined A variable identifier is lexically the same as a CSS ID at- above gives rise to the constraints shown in Figure 9. One tribute. The author can express constraints among global possible weighted-sum-better solution to these constraints is constrainable variables and element style properties using a that the heading is in 12 pt and the rest of the document new @constraint directive. There are also various global (including the paragraph) is in 8 pt. The problem is that built-in objects (e.g., Browser) with their own attributes that the paragraph element has “inherited” its value from its #p can be used. child,theBLOCKQUOTE element #q1. These extensions add considerable expressive power. For in- To capture the directionality of inheritance we use read- stance it is now simple to specify that all tables in the docu- only annotations [3] on variables that represent inherited at- ment have the same width, and that this is the smallest width tributes. Intuitively, a read-only variable v in a constraint c that allows all tables to have a reasonable layout: means that c should not be considered until the constraints @variable table-width; involving as an ordinary variable (i.e., not read-only) have v TABLE { constraint: width = table-width } been used to compute v’s value. Similarly we can specify two columns c1 and c2 in the same To model inheritance, we need to add the inheritance equali- (or different) tables have the same width (the smallest for ties with constraint importance of WEAK, and mark the vari- reasonably laying out both): able corresponding to the parent’s property as read-only. The read-only annotation ensures that the constraints are solved @constraint #c1[width] = #c2[width]; in an order corresponding to a top-down traversal of the doc- ument tree. Thus, the above example modifies the constraints It also allows the designer to express preferences in case the desired font is not available. For example adding in Figure 9 so that each font size variable on the right hand side has a read-only annotation. H1 { constraint: font-size >= 13pt } P { constraint: font-size >= 11pt } Extending CSS 2.0 We have seen how we can use hierarchical constraints to pro- to simple.css (Figure 2) will ensure that larger fonts are vide a declarative specification for CSS 2.0. There is, how- used if 13 pt and 11 pt fonts are not available. ever, another advantage in viewing CSS 2.0 in this light. The Finally, a sight-impaired user can express the strong desire to constraint viewpoint suggests a number of natural extensions have all font sizes greater than 12 pt:

6 * {constraint: font-size >= 12pt !important} Preconditions become even more expressive in the presence As long as the font size of an element is 12 pt or larger it will of support for CSS positioning [10] and a generalized not be changed, but smaller fonts will be enlarged. property [7].

Note that the style sheet author is not allowed to explicitly IMPLEMENTATION specify a constraint to be REQUIRED as this would admit the Prototype possibility of an unsatisfiable constraint system. Instead, RE- We have implemented a representative subset of CCSS to QUIRED constraints are generated implicitly for capturing re- demonstrate the additional expressiveness it provides to web lationships inherent in the structure of the layout, such as a designers. Our prototype is based on version 1.4a of Amaya table’s width being the sum of the widths of its columns. [8], the W3 Consortium’s browser. Amaya is built on top of Providing inequality constraints allows the author to con- Thot, a structured document editor, and has partial support trol the document appearance more precisely in the context for CSS1. Amaya is exceptionally easy to extend in some of browser capabilities and user preferences. Additionally, ways (e.g., adding new HTML tags), and provides a stable CCSS allows the author to give alternate style sheets for the base from which to build. same target media. Each style sheet can list preconditions for their applicability using a new @precondition direc- Our support for constraints in Amaya covers the two main tive. For efficiency, the precondition can only refer to vari- domains for constraints that we have discussed: table widths ous pre-defined variables. The values of these variables will (for illustrating page layout relationships) and font sizes (for be known (i.e. they will have specific values) at the time the illustrating the solution of systems involving inherited at- precondition is tested. For example: tributes). In our prototype, HTML and CSS statements can contain constraints and declare constrainable variables. In @precondition Browser[frame-width] >= 800px; HTML statements, constrainable variables, in addition to @precondition ColorMonitor = True; specific values, can be attached by name to element attributes We extend the style sheet @import directive to permit listing (e.g., to the “width” of a table column). When the constraints multiple style sheets per line, and the first applicable sheet is of the document force the values assigned to variables to used (the others are ignored). If no style sheet’s precondi- change, the browser updates its rendering of the current page, tions hold, none are imported. Consider the example direc- much as it does when the browser window is resized (which tive often caused the re-solve in the first place).

@import "wide.css", "tall.css", "small.css"; We have also extended Amaya to support preconditions on style sheets and the generalized “@import” CCSS rule. The If wide.css’s preconditions fail, but tall.css’s succeed, performance when switching among style sheets is similar to the layout uses tall.css. If, through the course of the user a reload, and when the style sheets are cached on disk, per- resizing the top-level browser frame, wide.css’s precondi- formance is good even when switching style sheets during an tions later become satisfied, the layout does not switch to that interactive resize. (It may be useful to provide background style sheet unless tall.css’s preconditions are no longer pre-fetching of alternate style-sheets to avoid latency when satisfied. That is, the choice among style sheets listed with they are first needed.) See Figure 10 for screen shots of an ex- one directive is only revisited when a currently-used style ample using our prototype’s support for both table layout and sheet is no longer applicable. preconditions. As the support for CSS improves in browsers, more significant variations will be possible through the use As an example, consider a style sheet for text with pictures. of our @precondition and extended @import directives. If the page is wide, the images should appear to the right of the text; if it is narrow, they should appear without text to the We compared the performance of our prototype browser to left; and if it is too small, the images should not appear at all. an unmodified version of Amaya 1.4a, both fully optimized, This can be encoded as: running on a PII/400 displaying across a 10Mbit network to a Tektronix X11 server on the same subnet. Our test case was /* wide.css */ a small example on local disk using seven style sheets. We @precondition Browser[frame-width] > 550px; IMG { float: right} executed 100 re-loads, and measured the total wall time con- sumed. The unmodified browser performed each re-load and /* tall.css */ re-render in 190 ms, while our prototype took only 250 ms @precondition Browser[frame-width] <= 600px; even when sized to select the last alternative style sheet in @precondition Browser[frame-height] > 550px; each of three @import directives. This performance penalty IMG { clear: both; float: none} is reasonable given the added expressiveness and features the prototype provides. /* small.css */ IMG { display: none } One of the most important benefits of re-framing CSS as con-

7 Figure 10: Screen shots of our prototype browser. In the view on the left, a narrow style sheet is in effect because the browser width 800 pixels, while on the right a wide style sheet is used. Interactively changing the browser width ≤ 1 dynamically switches between these two presentations. In both figures, the first column is 4 the width of the second column, which is twice the width of the last column. On the left, the table consumes 100% of the frame width, but on the right, the table width is the browser width minus 200 pixels. Also notice the changes in font size and text alignment. straints is that it provides an implementation approach for for choosing a single solution from among those that sat- even the standard CSS features. To simplify our prototype isfy all the required constraints. As mentioned earlier, this and ensure it remains a superset of CSS functionality, we comparator computes the error for a solution by summing currently do not treat old-style declarations as constraints, the product of the strength tuple and the error for each con- but instead rely on the existing implementation’s handling of straint that is unsatisfied. To model the CSS importance those rules. However, if designed into a browser from the rules in a hierarchy of constraint strengths, we encode the beginning, treating all CSS rules as syntactic sugar for un- symbolic levels of importance as tuples as well; for exam- derlying constraints will result in large savings in code and ple, USER-IMPORTANT is 1, 0, 0, 0, 0, 0 and BROWSER is h i complexity. The cascading rules would be completely re- 0, 0, 0, 0, 1, 0 . Thus, no matter what scalar error a BROWSER placed by the constraint solver’s more principled assignment hconstraint has,i it will never be satisfied if doing so would of values to variables, and the display engine need only use force a USER-IMPORTANT constraint to not be satisfied. Sim- those provided values, and redraw when the solver changes ilarly the last three components of the strength tuple are en- the current solution. coded as 10i, 10c, 10t .5 Since the Cassowary toolkit oper- ates on constraintsh withi strengths that are a single n-tuple, we Constraint Solving Algorithms internally use 9-tuples to represent strengths—for example, While the semantics of the constraints is independent of the algorithms used to satisfy them, for interactive applications 1, 0, 0, 0, 0, 0, 100, 101, 100 such as a web browser, we nevertheless must select an al- h i gorithm that is capable of efficiently finding solutions to the is the strength of a user-specified !important constraint constraints at interactive speeds. Our implementation uses whose selector only contains a single class name. two algorithms: Cassowary [4] and a restricted version of BAFSS [12]. BAFSS uses a dynamic programming approach to handle systems of font constraints which are binary (i.e., a constraint The Cassowary algorithm handles linear arithmetic equality with two variables) and for which the associated constraint and inequality constraints. The collection of constraints may graph is acyclic. For the font constraints implied by CSS, include cycles (i.e. simultaneous equalities and inequalities we are able to simplify the algorithm because all of the con- or redundant constraints) and conflicting preferences. Cas- straints relate a read-only size attribute in the parent element sowary is an incremental version of the simplex algorithm, a to the size attribute of a child element. Given this additional well-known and heavily studied technique for finding a so- restriction that all constraints are one-way, the algorithm is lution to a collection of linear equality and inequality con- straints that minimizes the value of a linear expression called 5This does not exactly match the CSS specificity rules. For example if the error in a constraint with strength WEAK,0,0,1 is 10 times greater the objective function. However, commonly available im- h i than the error in a conflicting constraint with strength WEAK,0,0,2 ,the plementations of the simplex algorithm are not suitable for first constraint will affect the final solution. By choosingh appropriatei error interactive applications such as a web browser. functions we can make this unlikely to occur in practice. However, the more general constraint hierarchy support may actually permit more desirable in- Cassowary supports the weighted-sum-better comparator [3] teractions rather than the strict strength ordering imposed by CSS.

8 simple: visit the variable nodes in topological order and as- designer desires and requirements, and a simple powerful sign each a value that greedily minimizes the error contribu- model for layout of complex objects, such as tables. The tion from that variable. simplest extension is to allow constraints in the presentation view of the document. (Providing constraints in the transfor- Both constraint solvers are implemented within the Casso- mation rules would seem to offer little advantage.) In the case wary Constraint Solving library [1]. of DSSSL a natural way to do this is to embed a constraint solver into Scheme (as in SCWM [2]). In the case of XSL, RELATED WORK since HTML is often used as the targeted visual rendering The most closely related research is our earlier work on the language, the simplest change is to augment that language to use of constraints for web page layout [5]. This system al- be HTML with CCSS style properties. Then the XSL trans- lowed the web page author to construct a document com- lator would simply generate HTML and a CCSS style sheet, posed of graphic objects and text. The layout of these ob- with a CCSS-enhanced browser still performing the dynamic jects and the text font size were described in a separate “lay- constraint solving, rendering, and interaction. out sheet” using linear arithmetic constraints and finite do- main constraints. Like CCSS, layout sheets had precondi- Regarding other user interface applications of constraints, tions, controlling their applicability. there is a long history of using constraints in interfaces and interactive systems, beginning with Ivan Sutherland’s pio- The work reported here, which focuses on how to combine neering Sketchpad system [17]. Constraints have also been constraint-based layout with CSS, is complementary to our used in several other layout applications. IDEAL [18] is an previous research. One of the major technical contributions early system specifically designed for page layout applica- here is to provide a declarative semantics for CSS based on tions. Harada, Witkin, and Baraff [11] describe the use of hierarchical constraints; this issue was not addressed in our physically-based modeling for a variety of interactive mod- prior work [5]. There are two fundamental differences be- eling tasks, including page layout. There are numerous sys- tween layout sheets and CCSS. Layout sheets are not style tems that use constraints for widget layout [15, 16], while sheets in the sense of CSS since they can only be used with a Badros [2] uses constraints for window layout. single document. Constraints only apply to named elements, and there is no concept of a style rule that applies to multiple CONCLUSIONS AND FUTURE WORK elements—the constraints that are used are exactly the con- straints that the author has specified. The other fundamental We have demonstrated that hierarchical constraints provide a difference between the earlier work [5] and CCSS is that the unifying, declarative semantics for CSS 2.0 and also suggest former has no analogue of the document tree. In essence, the a simplifying implementation strategy. Furthermore, view- document is modeled as a flat collection of objects; there is ing CSS from the constraint perspective suggests several nat- no notion of inheritance, and nearly all layout must be ex- ural extensions. We call the resulting extension CCSS— plicitly detailed in the layout sheet. Constraint Cascading Style Sheets. By allowing true con- straints and style sheet preconditions, CCSS increases the Cascading Style Sheets are not the only kind of style sheet. expressiveness of CSS 2.0 and, importantly, allows the de- The Document Style Semantics and Specification Language signer to write style sheets that combine more flexibly and (DSSSL) is an ISO standard for specifying the format of predictably with user preferences and browser restrictions. SGML documents. DSSSL is based on Scheme, and pro- We have demonstrated the feasibility of CCSS by modifying vides both a transformation language and a style language. the Amaya browser. However, substantial work remains to It is very powerful but complex to use. More recently, W3C develop an industrial-strength browser supporting full CCSS, has begun designing the XSL style sheet for use with XML in part because of Amaya’s lack of support for CSS 2.0. A documents. XSL is similar in spirit to DSSSL. PSL [13] is more complete implementation will be especially useful for another style sheet language; its expressiveness lies midway investigating the important issue of how well the constraint between that of CSS and XSL. The underlying application systems and solver scale to larger, more complicated designs model for all three is the same: take the document tree of that further exploit our constraint extensions. the original document and apply transformation rules from the style sheet in order to obtain the presentation view of the Apart from improving the current implementation, we have document, which is then displayable by the viewing device. two principal directions for further extensions to CCSS. The In the case of XSL, the usual presentation view is an HTML first is to increase the generality and solving capabilities document whose elements are annotated with style proper- of the underlying solver. For example, style sheet authors ties. should be able to arbitrarily annotate variables as read-only so that they have greater control over the interactions of None of these other style sheet languages allow true con- global variables. Additionally, virtually all CSS properties, straints. Extending any of them to incorporate constraints such as color and font weight, could be exposed to the con- would offer many of the same benefits as it does for CSS, straint solver once we integrate other algorithms into our namely, the ability to flexibly combine user, browser, and solving toolkit.

9 The second extension is to allow “predicate” selectors in 8. W3 Consortium. Amaya web browser software. Web style sheet rules. These selectors would permit an arbitrary page, October 1998. http://www.w3.org/Amaya. predicate to be tested in determining the applicability of a rule to an element in the document structure tree. Predicate 9. W3 Consortium. HTML 4.0 specification. Technical selectors can be viewed as a generalization of the existing report, W3 Consortium, 1998. http://www.w3.org/TR/ selectors; an H1 P selector is applied only to nodes n for REC-html40. which the predicate “n[type] = P and m parent-of n such ∃ 10. S. Furman and S. Isaacs. Positioning HTML elements that m[type] = H1” holds. These predicate selectors would with cascading style sheets. W3C Working Draft. allow the designer to take into account the attributes of the http://www.w3.org/TR/WD-positioning. selected element’s parents and children, thus, for instance, allowing the number of items in a list to affect the appear- 11. M. Harada, A. Witkin, and D. Baraff. Interactive ance of the list (as in an example used to motivate PSL [13]). physically-based manipulation of discrete/continuous models. In SIGGRAPH ’95 Conference Proceedings, A final important area for future work is the design, imple- pages 199–208, Los Angeles, August 1995. ACM. mentation, and user testing of graphical interfaces for writ- ing and debugging constraint cascading style sheets and web 12. R. Lin, K. Marriott, and P. Stuckey. Flexible font-size pages that use them. specification in Web documents. In Proceedings of the 22 Australasian Computer Science Conference, Auck- ACKNOWLEDGMENTS land, New Zealand, January 1999. Springer-Verlag. We thank and H˚akon Lie of the CSS group of the W3 Consortium for early feedback on these ideas and our 13. P. Marden, Jr. and E. Munson. PSL: An alternate ap- proposed extensions to CSS. This research has been funded proach to style sheet languages for the world wide web. in part by a US National Science Foundation Graduate Fel- Journal of Universal Computer Science, 4(10), 1998. lowship for Greg Badros and by NSF Grant No. IIS-9975990, http://www.cs.uwm.edu/˜multimedia. and in part by a grant from the Australian Research Council. 14. K. Marriott and P. Stuckey. Programming with Con- REFERENCES straints: An Introduction. The MIT Press, 1998. 1. G. Badros and A. Borning. The Cassowary linear arith- 15. B. Myers, D. Giuse, R. Dannenberg, B. Vander Zanden, metic constraint solving algorithm: Interface and im- D. Kosbie, E. Pervin, A. Mickish, and P. Marchal. Gar- plementation. Technical Report UW-CSE-98-06-04, net: Comprehensive support for graphical highly in- University of Washington, Seattle, Washington, June teractive user interfaces. IEEE Computer, November 1998. 1990. 2. G. Badros and M. Stachowiak. Scwm—The Scheme 16. B. Myers, R. McDaniel, R. Miller, A. Ferrency, Constraints Window Manager. Web page, 1997–1999. A. Faulring, B. Kyle, A. Mickish, A. Klimovitski, and http://scwm.mit.edu/. P. Doane. The Amulet environment: New models for 3. A. Borning, B. Freeman-Benson, and M. Wilson. Con- effective user interface software development. IEEE straint hierarchies. Lisp and Symbolic Computation, Transactions on Software Engineering, 23(6):347–365, 5(3):223–270, September 1992. June 1997. 17. I. Sutherland. Sketchpad: A man-machine graphical 4. A. Borning, K. Marriott, P. Stuckey, and Y. Xiao. Solv- communication system. In Proceedings of the Spring ing linear arithmetic constraints for user interface appli- Joint Computer Conference, pages 329–346. IFIPS, cations. In Proceedings of the 10th ACM Symposium on 1963. User Interface Software and Technology, pages 87–96, 1997. 18. C. Wyk. A high-level language for specifying pictures. ACM Transactions on Graphics, 1(2):163–182, April 5. A. Borning, R. Lin, and K. Marriott. Constraints for the 1982. web. In Proceedings of 1997 ACM Multimedia Confer- ence, pages 173–182, 1997.

6. B. Bos, H. Lie, C. Lilley, and I. Jacobs. Cascading style sheets, level 2. W3C Working Draft, January 1998. http://www.w3.org/TR/WD-css2/.

7. B. Bos, D. Raggett, and H. Lie. Frame-based layout via style sheets. W3C Working Draft. http://www.w3.org/ TR/WD-layout.

10