Contents
This chapter defines the processing model for tables in CSS. Partof this processing model is the layout. For the layout, this chapterintroduces two algorithms; the first, the fixed table layoutalgorithm, is well-defined, but the second, the automatic table layoutalgorithm, is not fully defined by this specification.
For the automatic table layout algorithm, some widely deployedimplementations have achieved relatively close interoperability.
Table layout can beused to represent tabular relationships between data. Authors specifythese relationships in thedocumentlanguage and can specify theirpresentation usingCSS 2.2.
In a visual medium, CSS tables can also be used to achieve specificlayouts. In this case, authors should not use table-related elementsin the document language, but should apply the CSS to the relevantstructural elements to achieve the desired layout.
Authors may specify the visual formatting of a table as arectangular grid of cells. Rows and columns of cells may be organizedinto row groups and column groups. Rows, columns, row groups, columngroups, and cells may have borders drawn around them (there are twoborder models in CSS 2.2). Authors may align data vertically orhorizontally within a cell and align data in all cells of a row orcolumn.
Example(s):
Here is a simple three-row, three-column table described in HTML 4:
<TABLE><CAPTION>This is a simple 3x3 table</CAPTION><TR> <TH>Header 1 <TD>Cell 1 <TD>Cell 2<TR> <TH>Header 2 <TD>Cell 3 <TD>Cell 4<TR> <TH>Header 3 <TD>Cell 5 <TD>Cell 6</TABLE>
This code creates one table (the TABLE element), threerows (the TR elements), three header cells (the TH elements),and six data cells (the TD elements). Note that the three columnsof this example are specified implicitly: there are as manycolumns in the table as required by header and data cells.
The following CSS rule centers the text horizontally in the headercells and presents the text in the header cells with a bold fontweight:
th { text-align: center; font-weight: bold }
The next rules align the text of the header cells on their baselineand vertically center the text in each data cell:
th { vertical-align: baseline }td { vertical-align: middle }
The next rules specify that the top row will be surrounded by a 3pxsolid blue border and each of the other rows will be surrounded by a1px solid black border:
table { border-collapse: collapse }tr#row1 { border: 3px solid blue }tr#row2 { border: 1px solid black }tr#row3 { border: 1px solid black }
Note, however, that the borders around the rows overlap where therows meet. What color (black or blue) and thickness (1px or 3px) willthe border between row1 and row2 be? We discuss this in the section onborder conflict resolution.
The following rule puts the table caption above the table:
caption { caption-side: top }
The preceding example shows how CSS works with HTML 4 elements;in HTML 4, the semantics of the various table elements (TABLE,CAPTION, THEAD, TBODY, TFOOT, COL, COLGROUP, TH, and TD) arewell-defined. In other document languages (such as XML applications),there may not be pre-defined table elements. Therefore, CSS 2.2 allowsauthors to"map" document language elements to table elements viathe'display' property. Forexample, the following rule makes the FOO element act like an HTMLTABLE element and the BAR element act like a CAPTION element:
FOO { display : table }BAR { display : table-caption }
We discuss the various table elements in thefollowing section. Inthis specification, the termtable element refers to any elementinvolved in the creation of a table. An
The CSS table model is based on the HTML4 table model, inwhich the structure of a table closely parallels the visual layout ofthe table. In this model, a table consists of an optional caption andany number of rows of cells. The table model is said to be "rowprimary" since authors specify rows, not columns, explicitly in thedocument language. Columns are derived once all the rows have beenspecified -- the first cell of each row belongs to the first column,the second to the second column, etc.). Rows and columns may begrouped structurally and this grouping reflected in presentation(e.g., a border may be drawn around a group of rows).
Thus, the table model consists of tables, captions, rows,
The CSS model does not require that thedocument language include elementsthat correspond to each of these components. For document languages(such as XML applications) that do not have pre-defined tableelements, authors must map document language elements to tableelements; this is done with the
Replaced elements with these
Elements with'display' setto 'table-column' or 'table-column-group' are not rendered (exactly asif they had 'display: none'), but they are useful, because they mayhave attributes which induce a certain style for the columns theyrepresent.
Thedefault style sheet for HTML4in the appendix illustrates the use of these values for HTML4:
table { display: table }tr { display: table-row }thead { display: table-header-group }tbody { display: table-row-group }tfoot { display: table-footer-group }col { display: table-column }colgroup { display: table-column-group }td, th { display: table-cell }caption { display: table-caption }
User agents mayignore these'display' property values forHTML table elements, since HTML tables may be rendered using otheralgorithms intended for backwards compatible rendering. However, thisis not meant to discourage the use of 'display: table' on other,non-table elements in HTML.
Document languages other than HTML may not contain all the elementsin the CSS 2.21 table model. In these cases, the "missing"elements must be assumed in order for the table model to work. Anytable element will automatically generate necessary anonymous tableobjects around itself, consisting of at least three nested objectscorresponding to a 'table'/'inline-table' element, a 'table-row'element, and a 'table-cell' element. Missing elements generateanonymous objects (e.g., anonymousboxes in visual table layout) according to the following rules:
For the purposes of these rules, the following terms are defined:
For the purposes of these rules, out-of-flow elements arerepresented as inline elements of zero width and height. Theircontaining blocks are chosen accordingly.
The following steps are performed in three stages.
Example(s):
In this XML example, a 'table' element is assumed to contain theHBOX element:
<HBOX> <VBOX>George</VBOX> <VBOX>4287</VBOX> <VBOX>1998</VBOX></HBOX>
because the associated style sheet is:
HBOX { display: table-row }VBOX { display: table-cell }
Example(s):
In this example, three 'table-cell' elements are assumed to containthe text in the ROWs. Note that the text is further encapsulated inanonymous inline boxes, as explained invisual formatting model:
<STACK> <ROW>This is the <D>top</D> row.</ROW> <ROW>This is the <D>middle</D> row.</ROW> <ROW>This is the <D>bottom</D> row.</ROW></STACK>
The style sheet is:
STACK { display: inline-table }ROW { display: table-row }D { display: inline; font-weight: bolder }
Table cells may belong to two contexts: rows and columns. However,in the source document cells are descendants of rows, never ofcolumns. Nevertheless, some aspects of cells can be influenced bysetting properties on columns.
The following properties apply to column and column-group elements:
Example(s):
Here are some examples of style rules that set properties oncolumns. The first two rules together implement the "rules" attributeof HTML 4 with a value of "cols". The third rule makes the "totals"column blue, the final two rules shows how to make a column a fixedsize, by using thefixed layoutalgorithm.
col { border-style: none solid }table { border-style: hidden }col.totals { background: blue }table { table-layout: fixed }col.totals { width: 5em }
In terms of the visual formatting model, a table can behave like ablock-level (for 'display:table') orinline-level (for'display: inline-table') element.
In both cases, the table generates a principal block container boxcalled thetable wrapper box thatcontains the table box itself and any caption boxes (in documentorder).Thetable box is a block-level boxthat contains thetable's internal table boxes.The caption boxes are principal block-level boxes that retain their owncontent, padding, margin, and border areas, and are rendered as normalblock boxes inside the table wrapper box. Whether the caption boxes are placedbefore or after the table box is decided by the 'caption-side'property, as described below.
The table wrapper box is block-level for 'display: table', andinline-level; for 'display: inline-table'. The table wrapper boxestablishes a block formatting context, and the table box establishesa table formatting context. The table box (not thetable wrapper box) is used when doing baselinevertical alignment for an 'inline-table'. The width of the table wrapperbox is the border-edge width of the table box inside it, as describedby section 17.5.2. Percentages on 'width' and 'height' on the table arerelative to the table wrapper box's containing block, not the table wrapper boxitself.
The computed values of properties 'position', 'float', 'margin-*','top', 'right', 'bottom', and 'left' on the table element are used onthe table wrapper box and not the table box; all other values ofnon-inheritable properties are used on the table box and not the tablewrapper box. (Where the table element's values are not used on thetable and table wrapper boxes, the initial values are used instead.)
Diagram of a table with a caption above it.
Name: | caption-side |
---|---|
Value: | top | bottom |inherit |
Initial: | top |
Applies to: | 'table-caption' elements |
Inherited: | yes |
Percentages: | N/A |
Media: | visual |
Computed value: | as specified |
This property specifies the position of the caption box withrespect to the table box. Values have the following meanings:
Note: CSS2 described a different width andhorizontal alignment behavior. That behavior will be introduced inCSS3 using the values 'top-outside' and 'bottom-outside' on thisproperty.
To align caption content horizontally within the caption box, usethe'text-align' property.
Example(s):
In this example, the
caption { caption-side: bottom; width: auto; text-align: left }
Internal table elements generate rectangularboxes which participate in thetable formatting context established by the table box. These boxeshave content and borders and cells have padding as well. Internaltable elements do not have margins.
The visual layout of these boxes is governed by a rectangular,irregular grid of rows and columns. Each box occupies a whole numberof grid cells, determined according to the following rules. Theserules do not apply to HTML 4 or earlier HTML versions; HTML imposesits own limitations on row and column spans.
The edges of the rows, columns, row groups and column groups in thecollapsing borders model coincidewith the hypothetical grid lines on which the borders of the cells arecentered. (And thus, in this model, the rows together exactly coverthe table, leaving no gaps; ditto for the columns.) In theseparated borders model, the edgescoincide with theborder edges ofcells. (And thus, in this model, there may be gaps between the rows,columns, row groups or column groups, corresponding to the
Note. Positioning and floating of table cellscan cause them not to be table cells anymore, according to the rulesinsection 9.7. When floatingis used, therules on anonymous table objects may cause ananonymous cell object to be created as well.
Here is an example illustrating rule 5. The following illegal (X)HTML snippet defines conflicting cells:
<table><tr><td>1 </td><td rowspan="2">2 </td><td>3 </td><td>4 </td></tr><tr><td colspan="2">5 </td></tr></table>
User agents are free to visually overlap the cells, as in thefigure on the left, or to shift the cell to avoid the visualoverlap, as in the figure on the right.
Two possiblerenderings of an erroneous HTML table.
For the purposes of finding the background of each table cell, thedifferent table elements may be thought of as being on sixsuperimposed layers. The background set on an element in one of thelayers will only be visible if the layers above it have a transparentbackground.
Schema of table layers.
A "missing cell" is a cell in the row/column grid that is notoccupied by an element or pseudo-element. Missing cells are renderedas if an anonymous table-cell box occupied their position in the grid.
In the following example, the first row contains four non-emptycells, but the second row contains only one non-empty cell, and thusthe table background shines through, except where a cell from thefirst row spans into this row. The following HTML code and style rules
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"><HTML> <HEAD> <TITLE>Table example</TITLE> <STYLE type="text/css"> TABLE { background: #ff0; border: solid black; empty-cells: hide } TR.top { background: red } TD { border: solid black } </STYLE> </HEAD> <BODY> <TABLE> <TR> <TD> 1 <TD rowspan="2"> 2 <TD> 3 <TD> 4 <TR> <TD> 5 <TD> </TABLE> </BODY></HTML>
might be formatted as follows:
Table with empty cells in the bottom row.
Note that if the table has 'border-collapse: separate', thebackground of the area given by the
CSS does not define an "optimal" layout for tables since, in manycases, what is optimal is a matter of taste. CSS does defineconstraints that user agents must respect when laying out a table.User agents may use any algorithm they wish to do so, and are free toprefer rendering speed over precision, except when the "fixed layoutalgorithm" is selected.
Note that this section overrides the rules that apply tocalculating widths as described insection 10.3. Inparticular, if the margins of a table are set to '0' and the width to'auto', the table will not automatically size to fill its containingblock. However, once the calculated value of 'width' for the table isfound (using the algorithms given below or, when appropriate, someother UA dependent algorithm) then the other parts of section 10.3 doapply. Therefore a tablecan be centered using left and right'auto' margins, for instance.
Future updates of CSS may introduce ways of making tablesautomatically fit their containing blocks.
Name: | table-layout |
---|---|
Value: | auto | fixed |inherit |
Initial: | auto |
Applies to: | 'table' and 'inline-table' elements |
Inherited: | no |
Percentages: | N/A |
Media: | visual |
Computed value: | as specified |
The'table-layout'property controls the algorithm used to lay out the table cells, rows,and columns. Values have the following meaning:
The two algorithms are described below.
With this (fast) algorithm, the horizontal layout of the table doesnot depend on the contents of the cells; it only depends on thetable's width, the width of the columns, and borders or cell spacing.
The table's width may be specified explicitly with the
Example(s):
If a UA supports fixed table layout when 'width' is 'auto', thefollowing will create a table that is 4em narrower than its containingblock:
table { table-layout: fixed; margin-left: 2em; margin-right: 2em }
In the fixed table layout algorithm, the width of each column isdetermined as follows:
The width of the table is then the greater of the value of the'width' property for the tableelement and the sum of the column widths (plus cell spacing orborders). If the table is wider than the columns, the extra spaceshould be distributed over the columns.
If a subsequent row has more columns than the greater of the numberdetermined by the table-column elements and the number determined bythe first row, thenadditional columns may not be rendered. CSS 2.2 does not definethe width of the columns and the table if theyare rendered. When using 'table-layout:fixed', authors should not omit columns from the first row.
In this manner, the user agent can begin to lay out the table oncethe entire first row has been received. Cells in subsequent rows donot affect column widths. Any cell that has content that overflowsuses the'overflow' property todetermine whether to clip the overflow content.
In this algorithm (which generally requires no more than twopasses), the table's width is given by the width of its columns (andinterveningborders). This algorithm reflectsthe behavior of several popular HTML user agents at the writing ofthis specification. UAs are not required to implement this algorithmto determine the table layout in the case that
Input to the automatic table layout must only include the width ofthe containing block and the content of, and any CSS properties seton, the table and any of its descendants.
Note. This may be defined in more detail inCSS3.
The remainder of this section is non-normative.
This algorithm may be inefficient since it requires the user agentto have access to all the content in the table before determining thefinal layout and may demand more than one pass.
Column widths are determined as follows:
Calculate the minimum content width (MCW) of each cell: the formatted content may span any number of lines but may not overflow the cell box. If the specified'width' (W) of the cell is greater than MCW, W is the minimum cell width. A value of 'auto' means that MCW is the minimum cell width.
Also, calculate the "maximum" cell width of each cell: formatting the content without breaking lines other than where explicit line breaks occur.
For each column, determine a maximum and minimum column width from the cells that span only that column. The minimum is that required by the cell with the largest minimum cell width (or the column'width', whichever is larger). The maximum is that required by the cell with the largest maximum cell width (or the column'width', whichever is larger).
For each cell that spans more than one column, increase the minimum widths of the columns it spans so that together, they are at least as wide as the cell. Do the same for the maximum widths. If possible, widen all spanned columns by approximately the same amount.
For each column group element with a 'width' other than 'auto', increase the minimum widths of the columns it spans, so that together they are at least as wide as the column group's 'width'.
This gives a maximum and minimum width for each column.
The caption width minimum (CAPMIN) is determined by calculating foreach caption the minimum caption outer width as the MCW of ahypothetical table cell that contains the caption formatted as"display: block". The greatest of the minimum caption outer widths isCAPMIN.
Column and captionwidths influence the final table width as follows:
A percentage value for a column width is relative to the tablewidth. If the table has 'width: auto', a percentage represents aconstraint on the column's width, which a UA should try to satisfy.(Obviously, this is not always possible: if the column's width is'110%', the constraint cannot be satisfied.)
Note. In this algorithm, rows (and rowgroups) and columns (and column groups) both constrain and areconstrained by the dimensions of the cells they contain. Setting thewidth of a column may indirectly influence the height of a row, andvice versa.
The height of a table is given by the
Note. Futureupdates of CSS may specify this further.
The height of a 'table-row' element's box is calculated once theuser agent has all the cells in the row available: it is the maximumof the row's computed'height',the computed'height' of eachcell in the row,and the minimum height (MIN) required by the cells. A
In CSS 2.2, the height of a cell box is the minimum heightrequired by the content. The table cell's
CSS 2.2 does not specify how cells that span more than one rowaffect row height calculations except that the sum of the row heightsinvolved must be great enough to encompass the cell spanning the rows.
The'vertical-align'property of each table cell determines its alignment within the row.Each cell's content has a baseline, a top, a middle, and a bottom, asdoes the row itself. In the context of tables, values for
The baseline of a cell is the baseline of the first in-flowline box in the cell, or the firstin-flow table-row in the cell, whichever comes first. If there is nosuch line box or table-row, the baseline is the bottom of content edgeof the cell box. For the purposes of finding a baseline, in-flow boxeswith a scrolling mechanisms (see the
The maximumdistance between the top of the cell box and the baseline over allcells that have 'vertical-align: baseline' is used to set the baselineof the row. Here is an example:
Diagram showing the effect of various values of 'vertical-align' on table cells.
Cell boxes 1 and 2 are aligned at their baselines. Cell box 2 hasthe largest height above the baseline, so that determines the baselineof the row.
If a row has no cell box aligned to its baseline, the baseline ofthat row is the bottom content edge of the lowest cell in the row.
To avoid ambiguous situations, the alignment of cells proceeds inthe following order:
Cell boxes that are smaller than the height of the row receiveextra top or bottom padding.
The cell in this example has a baseline below its bottom border:
div { height: 0; overflow: hidden; }<table> <tr> <td> <div> Test </div> </td> </tr></table>
The horizontal alignment of inline-level content within a cellbox can be specified by the value ofthe'text-align' property onthe cell.
The'visibility' propertytakes the value 'collapse' for row, row group, column, and columngroup elements. This value causes the entire row or column to beremoved from the display, and the space normally taken up by the rowor column to be made available for other content. Contents of spannedrows and columns that intersect the collapsed column or row areclipped. The suppression of the row or column, however, does nototherwise affect the layout of the table. This allows dynamic effectsto remove table rows or columns without forcing a re-layout of thetable in order to account for the potential change in columnconstraints.
There are two distinct models for setting borders on table cells inCSS. One is most suitable for so-called
Name: | border-collapse |
---|---|
Value: | collapse | separate |inherit |
Initial: | separate |
Applies to: | 'table' and 'inline-table' elements |
Inherited: | yes |
Percentages: | N/A |
Media: | visual |
Computed value: | as specified |
This property selects a table's border model. The value 'separate'selects the separated borders border model. The value 'collapse'selects the collapsing borders model. The models are described below.
Name: | border-spacing |
---|---|
Value: | <length><length>? |inherit |
Initial: | 0 |
Applies to: | 'table' and 'inline-table' elements* |
Inherited: | yes |
Percentages: | N/A |
Media: | visual |
Computed value: | two absolute lengths |
*) Note: user agents may also apply the'border-spacing' property to 'frameset' elements. Which elements are'frameset' elements is not defined by this specification and is up tothe document language. For example, HTML4 defines a <FRAMESET>element, and XHTML 1.0 defines a <frameset> element. The'border-spacing' property on a 'frameset' element can be thus used asa valid substitute for the non-standard 'framespacing' attribute.
The lengths specify the distance that separates adjoining cellborders. If one length is specified, it gives both the horizontal andvertical spacing. If two are specified, the first gives the horizontalspacing and the second the vertical spacing. Lengths may not benegative.
The distance between the table border and the borders of the cellson the edge of the table is the table's padding for that side, plusthe relevant border spacing distance. For example, on the right handside, the distance ispadding-right +horizontalborder-spacing.
The width of the table is the distance from the left inner paddingedge to the right inner padding edge (including the border spacing butexcluding padding and border).
However, in HTML and XHTML1, the width of the <table>element is the distance from the left border edge to the right borderedge.
Note: In CSS3 this peculiar requirementwill be defined in terms of UA style sheet rules and the 'box-sizing'property.
In this model, each cell has an individual border. The
Example(s):
The table in the figure below could be the result of a style sheetlike this:
table { border: outset 10pt; border-collapse: separate; border-spacing: 15pt }td { border: inset 5pt }td.special { border: inset 10pt } /* The top-left cell */
A table with'border-spacing' set to a length value. Note that each cell has its own border, and the table has a separate border as well.
Name: | empty-cells |
---|---|
Value: | show | hide |inherit |
Initial: | show |
Applies to: | 'table-cell' elements |
Inherited: | yes |
Percentages: | N/A |
Media: | visual |
Computed value: | as specified |
In the separated borders model, this property controls therendering of borders and backgrounds around cells that have no visiblecontent. Empty cells and cells with the
When this property has the value 'show', borders and backgroundsare drawn around/behind empty cells (like normal cells).
A value of 'hide' means that no borders or backgrounds are drawnaround/behind empty cells (see point 6 in17.5.1). Furthermore, if all the cells in arow have a value of 'hide' and have no visible content, then the rowhas zero height and there is vertical border-spacing on only one sideof the row.
Example(s):
The following rule causes borders and backgrounds to be drawnaround all cells:
table { empty-cells: show }
In the collapsing border model, it is possible to specify bordersthat surround all or part of a cell, row, row group, column, andcolumn group. Borders for HTML's "rules" attribute can be specifiedthis way.
Borders are centered on the grid lines between the cells. Useragents must find a consistent rule for rounding off in the case of anodd number of discrete units (screen pixels, printer dots).
The diagram below shows how the width of the table, the widths ofthe borders, the padding, and the cell width interact. Their relationis given by the following equation, which holds for every row of thetable:
row-width = (0.5 *border-width0)+padding-left1 +width1 +padding-right1 +border-width1 +padding-left2 +...+padding-rightn + (0.5 *border-widthn)
Heren is the number of cells in the row,padding-lefti andpadding-righti refer to the left(resp., right) padding of celli, andborder-widthi refers to the borderbetween cellsi andi + 1.
UAs must compute an initial left and right border width for thetable by examining the first and last cells in the first row of thetable. The left border width of the table is half of the first cell'scollapsed left border, and the right border width of the table is halfof the last cell's collapsed right border. If subsequent rows havelarger collapsed left and right borders, then any excess spills intothe margin area of the table.
The top border width of the table is computed by examining allcells who collapse their top borders with the top border of the table.The top border width of the table is equal to half of the maximumcollapsed top border. The bottom border width is computed by examiningall cells whose bottom borders collapse with the bottom of the table.The bottom border width is equal to half of the maximum collapsedbottom border.
Any borders that spill into the margin are taken into account whendetermining if the table overflows some ancestor (see
Schema showing the widths of cells and borders and the padding of cells.
Note that in this model, the width of the table includes half thetable border. Also, in this model, a table does not have padding (butdoes have margins).
CSS 2.2 does not define where the edge of a background on atable element lies.
In the collapsing border model, borders at every edge of every cellmay be specified by border properties on a variety of elements thatmeet at that edge (cells, rows, row groups, columns, column groups,and the table itself), and these borders may vary in width, style, andcolor. The rule of thumb is that at each edge the most "eye catching"border style is chosen, except that any occurrence of the style'hidden' unconditionally turns the border off.
The following rules determine which border style "wins" in case ofa conflict:
Example(s):
The following example illustrates the application of theseprecedence rules. This style sheet:
table { border-collapse: collapse; border: 5px solid yellow; }*#col1 { border: 3px solid black; }td { border: 1px solid red; padding: 1em; }td.cell5 { border: 5px dashed blue; }td.cell6 { border: 5px solid green; }
with this HTML source:
<TABLE><COL id="col1"><COL id="col2"><COL id="col3"><TR id="row1"> <TD> 1 <TD> 2 <TD> 3</TR><TR id="row2"> <TD> 4 <TD> 5 <TD> 6</TR><TR id="row3"> <TD> 7 <TD> 8 <TD> 9</TR><TR id="row4"> <TD> 10 <TD> 11 <TD> 12</TR><TR id="row5"> <TD> 13 <TD> 14 <TD> 15</TR></TABLE>
would produce something like this:
An example of a table with collapsed borders.
Example(s):
Here is an example of hidden collapsing borders:
Table with two omitted internal borders.
HTML source:
<TABLE><TR><TD>foo</TD> <TD>bar</TD></TR><TR><TD>foo</TD> <TD>bar</TD></TR></TABLE>
Some of the values of the
[8]ページ先頭