XML can contain a wide variety of data, including tabular data. Since XML has no predefined DTD which can tell a browser how such data must be presented, it's up to CSS to present it as a normal HTML table. In this post I'm going to show you how to write a CSS file for making an XML structure appear as an HTML table. First of all, we need an XML structure to work with, like the following:
<data> <data-caption>Caption</data-caption> <data-row> <data-header>Header 1</data-header> <data-header>Header 2</data-header> <data-header>Header 3</data-header> </data-row> <data-row> <data-cell>Datum</data-cell> <data-cell>Datum</data-cell> <data-cell>Datum</data-cell> </data-row> <!--more rows--> </data>
We have several elements here:
data
: corresponds totable
data-caption
: corresponds tocaption
data-row
: corresponds totr
data-header
: corresponds toth
data-cell
: corresponds totd
Each element must have a well-defined role for its display
property:
table
table-caption
table-row
table-cell
table-cell
Now we can write our CSS styles:
data { display: table; width: 30em; border-collapse: collapse; border-spacing: 0; border: 2px solid gray; margin: 1em; table-layout: fixed; } data-caption { display: table-caption; text-align: center; font: 1.5em Georgia, serif; color: gray; padding-bottom: 4px; } data-row { display: table-row; } data-row:nth-child(odd) { background: #ffc; } data-header, data-cell { display: table-cell; padding: 0.3em; border: 1px solid gray; vertical-align: top; text-align: center; } data-header { font-weight: bold; background: gray; color: #fff; }
Once set our display roles, the actual styling of an XML table is identical to its HTML counterpart. You can see the demo below.