The Blue Cup's tables are now well built: they have a head, groups, a foot, merged cells and all the accessibility information. But if you open menu.html in the browser, they still look like a rough draft: no borders, cells crammed together and prices aligned to the left, where they are hard to compare. In this lesson, the last in the module, you will take a practical sneak preview of CSS applied to tables: borders and how they collapse, cell padding, alignment (with numbers on the right), alternating rows in two colours, styles for the head and the foot, columns highlighted with col, the position of the caption and the width of the table. You will also see the presentational attributes that used to be used for all of this and why you should no longer use them. The aim is to give the menu a professional look, even though the proper study of CSS comes in Module 8.
Contents
- A sneak preview of CSS: the
styleblock - Goodbye to presentational attributes
- Borders:
borderandborder-collapse - Inner spacing:
padding - Alignment:
text-alignandvertical-align - Zebra rows with
:nth-child - Styling the head, the group rows and the foot
- Highlighting columns with
col - The caption:
caption-side - The width of the table
- Project: a professional-looking menu
A sneak preview of CSS: the style block
CSS (Cascading Style Sheets) is the language that decides how HTML elements look. You will study it in Module 8, Integrating HTML and CSS, where you will learn how to link it properly and the different ways of writing it. For this lesson you will use the quickest way to try it out on a single page: a style element inside the head.
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Menu | The Blue Cup</title>
<style>
th, td {
border: 1px solid #c8d3e0;
}
</style>
</head>How to read a CSS rule:
| Part | In the example | Meaning |
|---|---|---|
| Selector | th, td |
Which elements it applies to: all th and all td elements (the comma separates selectors) |
| Braces | { … } |
They contain the declarations |
| Property | border |
Which characteristic is changed |
| Value | 1px solid #c8d3e0 |
What it ends up like: 1 pixel, solid line, bluish-grey colour |
| Semicolon | ; |
Ends each declaration |
Some details you will come across in the examples:
- Colours are written in hexadecimal notation:
#followed by six digits (two for red, two for green and two for blue).#ffffffis white;#1f4e79, The Blue Cup's dark blue. - Measurements use units such as
px(pixels) orem(relative to the text size:0.5emis half the height of a letter). - CSS comments are written between
/*and*/.
This is temporary. A
styleblock only affects the page it's on; if you wanted the same look inindex.html, you would have to copy it. The right way is an external stylesheet,css/styles.css, shared by every page. In Linking CSS to HTML and Inline, Internal and External CSS (Module 8) you will move this code into that file.
Goodbye to presentational attributes
In old HTML, the appearance of tables was controlled with attributes. You will still find them in legacy code, in old tutorials and in emails:
<!-- Old HTML: DON'T use it -->
<table border="1" cellpadding="8" cellspacing="0" width="100%" bgcolor="#eeeeee">
<tr bgcolor="#1f4e79">
<th align="left">Product</th>
<th align="right">Price</th>
</tr>
…
</table>They are all obsolete in HTML5. Each one has its CSS equivalent:
| Obsolete attribute | What it did | CSS equivalent |
|---|---|---|
border="1" |
Borders on the table and cells | border on table, th and td |
cellpadding="8" |
Inner spacing of the cells | padding on th and td |
cellspacing="0" |
Spacing between cells | border-collapse: collapse or border-spacing |
bgcolor="…" |
Background colour | background-color |
align="right" |
Horizontal alignment | text-align |
valign="top" |
Vertical alignment | vertical-align |
width="100%" |
Width of the table or cell | width |
frame, rules |
Which outer and inner borders were drawn | border on the specific elements |
summary |
Summary for screen readers | caption and a descriptive paragraph (previous lesson) |
Why give them up, if browsers still understand them?
- Separation of content and presentation: the HTML says what each thing is; the CSS, how it looks. Changing the design shouldn't force you to touch every table.
- Repetition: with attributes, every table and every cell carries its own appearance. With CSS, a single rule styles every table on the site.
- Capabilities: CSS can do things attributes never could, such as automatic alternating rows or changes depending on the screen size.
- Validity: the validator flags these attributes as errors.
Borders: border and border-collapse
To see the grid, give the cells borders:
If you try it, you will see an odd effect: double lines. Each cell draws its own border, and between one cell and the next there's the 2-pixel gap you saw in Basic Table Structure. The solution is the table's border-collapse property:
| Value | Result |
|---|---|
separate (default) |
Each cell has its own border, with a gap between them (controlled with border-spacing) |
collapse |
The borders of neighbouring cells merge into a single line, with no gaps |
With collapse, the table displays a clean grid of single lines. It's what you want almost every time.
Inner spacing: padding
With the borders in place, the text is squashed up against the lines. padding adds space inside each cell, between the border and the content:
With two values, the first is the space at the top and bottom and the second the space on the left and right. Here, half a letter vertically and three quarters horizontally. Using em makes the space grow if the user increases the text size. (Padding and borders are part of the box model, which you will study in The Box Model, Module 8.)
Alignment: text-align and vertical-align
Remember the default styles: th centred and td on the left. A menu calls for something different:
- Text on the left, including the headers, so that each title lines up with its column.
- Numbers on the right. Right-aligned figures put units under units and cents under cents, so they can be compared at a glance. It's the convention on any invoice or bank statement.
As CSS doesn't know which cells contain prices, mark them with a class, as you already did with block or old-price in Module 2:
th, td {
text-align: left;
vertical-align: top;
}
.price {
text-align: right;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}text-align: leftaligns all the headers and data to the left..price(with a full stop) selects the elements withclass="price". As a class selector is more specific than a tag selector, it wins over the previous rule and those cells end up on the right. (Specificity is explained in Basic CSS Selectors.)white-space: nowrapstops "€1.40" from being split across two lines if the column gets narrower.font-variant-numeric: tabular-numsasks the font for fixed-width digits, so that a "1" takes up the same space as an "8" and the columns line up exactly.vertical-align: topplaces the content at the top of the cell. With cells of several lines (such as the allergens) or cells merged withrowspan, this reads better than centred.
And the "Price" header? It also gets the price class, so that it's aligned to the right, above its figures.
Zebra rows with :nth-child
Zebra rows alternate two background colours so that the eye doesn't skip a row when scanning a wide table. They are created with the :nth-child() pseudo-class, which selects elements by their position among their siblings:
tbody trselects the rows that are inside atbody(a space between selectors means "inside"). That way, the head and the foot aren't affected.:nth-child(even)keeps the ones in an even position (2nd, 4th, 6th…). There's alsooddand formulas such as3n(every third one).rgba(31, 78, 121, 0.06)is the brand blue at just 6% opacity: a very soft shade. The transparency will be an advantage when highlighting columns, as you will see shortly.
A detail with several tbody elements: the position is counted within each group. On the menu, the category row is the 1st in its tbody, so the first product is the 2nd (even, coloured), the second the 3rd (no colour), and so on. Each group starts with the same pattern, which is exactly what you want.
Styling the head, the group rows and the foot
Thanks to the structure from the previous lessons, you can style each area without adding a single class:
thead th {
background-color: #1f4e79;
color: #ffffff;
}
th[scope="rowgroup"] {
background-color: #dce6f0;
color: #1f4e79;
text-transform: uppercase;
letter-spacing: 0.05em;
}
tbody th[scope="row"] {
font-weight: normal;
}
tfoot td {
font-size: 0.9em;
font-style: italic;
background-color: #f7f7f7;
}thead th: the headers in the head, with a dark blue background and white text. When choosing colours, make sure there's sufficient contrast between text and background (you will see this in Web Accessibility Basics); white on dark blue easily passes.th[scope="rowgroup"]: an attribute selector, which picks thethelements whosescopeattribute isrowgroup. These are the category rows. Notice how the accessibility work from the previous lesson now serves as a hook for styling. As a cell's background is painted on top of its row's, these cells cover the zebra colour.text-transform: uppercasedisplays the categories in capitals visually only: the HTML still says "Black coffees". Never type in capitals in the HTML to achieve a visual effect.tbody th[scope="row"]: the product names are still row headers, but without bold, so that the menu doesn't look cluttered. The meaning doesn't change; only the appearance.tfoot td: the footnote, smaller, in italics and with a very light grey background, so that it reads as a clarification.
Highlighting columns with col
In Table Head, Body and Foot you added <col class="col-price"> to the menu. Now you put it to use:
The whole price column gets a cream background and a fixed width, without touching a single cell. But col has an important limitation: columns don't contain the cells (remember, HTML thinks in rows), so they only accept a handful of properties:
Property on col/colgroup |
Does it work? |
|---|---|
background-color |
Yes |
width |
Yes |
border |
Yes, but only with border-collapse: collapse |
visibility: collapse |
Yes (hides the column) |
text-align, color, font-weight, padding… |
No |
That's why the prices are aligned with the price class on the cells and not with col.
Why the zebra rows are semi-transparent
The browser paints a table's backgrounds in layers, from the bottom up:
graph BT
A["1. table"] --> B["2. colgroup"]
B --> C["3. col"]
C --> D["4. thead / tbody / tfoot"]
D --> E["5. tr"]
E --> F["6. td / th (the top layer)"]
The rows' background (tr) sits above the columns' background (col). If the zebra rows had an opaque colour, they would cover the price column on the even rows, and the highlighting would appear striped. With a semi-transparent colour (rgba with 0.06 opacity), the column's cream still shows through the row's soft blue. For the same reason, the background of the head, category and foot cells (layer 6) covers the column: that way those rows keep their own colour.
The caption: caption-side
By default, the caption is displayed centred above the table. With CSS you can change its appearance and its position:
caption {
caption-side: top;
text-align: left;
font-weight: bold;
padding: 0.5em 0;
color: #1f4e79;
}caption-sideacceptstop(above, the default value) orbottom(below the table, like a figure caption in a book).- Changing the visual position doesn't change the code: the
captionis still the first child oftableand the screen reader still announces it first. text-align: leftaligns it with the left edge of the table, which usually looks tidier than centred.
The width of the table
By default, a table is just wide enough for its content. For the menu, it's better for it to take up the available width, but without stretching endlessly on very wide screens:
width: 100%takes up the full width of the containing element (here, the section'sdiv).max-width: 48emlimits the width: beyond that, the rows would be so long that they would be hard to follow with your eye.margin-bottom: 2emseparates the table from the content that follows.
If you want the browser to respect exactly the widths you set on
colinstead of calculating them from the content, there's thetable-layout: fixedproperty. It's useful for very large tables, because they are also drawn faster. The menu doesn't need it.
And on mobile? A four-column table fits reasonably well; an eight-column one, like the opening hours, doesn't. Adapting tables to small screens is part of Module 9, Responsive Web Design.
Project: a professional-looking menu
- Marking the price cells
In menu.html, add class="price" to the "Price" header and to every price cell in the menu table and the lunch menu table. For example:
<tr>
<th scope="col">Product</th>
<th scope="col">Size</th>
<th scope="col">Allergens</th>
<th scope="col" class="price">Price</th>
</tr>
…
<tr>
<th scope="row">Espresso</th>
<td>30 ml</td>
<td>None</td>
<td class="price">€1.40</td>
</tr>
…
<th id="lunch-price" class="price">Price</th>
…
<td headers="lunch-price" rowspan="6" class="price">€9.50</td>In total: two headers and twelve cells (eleven products and the lunch menu price). Use VS Code's search (Ctrl + F) with the text >€ so that you don't miss any.
- The style block
Add this style block at the end of the head in menu.html, after the title:
<style>
/* Temporary table styles.
They will be moved to css/styles.css in Module 8 */
table {
border-collapse: collapse;
width: 100%;
max-width: 48em;
margin-bottom: 2em;
}
caption {
text-align: left;
font-weight: bold;
padding: 0.5em 0;
color: #1f4e79;
}
th, td {
border: 1px solid #c8d3e0;
padding: 0.5em 0.75em;
text-align: left;
vertical-align: top;
}
thead th {
background-color: #1f4e79;
color: #ffffff;
}
tbody tr:nth-child(even) {
background-color: rgba(31, 78, 121, 0.06);
}
th[scope="rowgroup"] {
background-color: #dce6f0;
color: #1f4e79;
text-transform: uppercase;
letter-spacing: 0.05em;
}
tbody th[scope="row"] {
font-weight: normal;
}
.price {
text-align: right;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
col.col-price {
background-color: #fff6e0;
width: 6em;
}
tfoot td {
font-size: 0.9em;
font-style: italic;
background-color: #f7f7f7;
}
</style>Save and open menu.html with Live Server. The menu now looks like a real café's:
- A blue head with white text and the table caption aligned to the left.
- Categories in a light blue band, in capitals.
- Very soft alternating rows and the price column highlighted in cream, with the figures aligned to the right.
- A footnote in small italic text.
- The lunch menu
The lunch menu shares all the rules, because the selectors are general (table, th, td, thead th…). There's just one detail: its row headers ("Starter", "Main"…) use headers instead of scope="row", so they are still bold. In this case that's desirable: they are the names of the courses and they stand out from the options. And since "€9.50" spans six rows with vertical-align: top, the price appears at the top, next to the starter.
- Experiment
Try these experiments and then undo them:
- Remove
border-collapse: collapseand look at the double lines. - Change the zebra row colour to an opaque one,
#e8eef5, and see how the price column becomes striped. - Try
caption-side: bottomoncaption. - Add
text-align: righttocol.col-priceand check that it has no effect.
State of the project at the end of the module
| Page | What's new in Module 4 |
|---|---|
menu.html |
A "Price list" table (div#prices) with caption, colgroup, head, three groups (#specialities, #coffees, #milk-coffees), size and allergen columns and a foot with VAT and allergen information; a lunch menu table (div#lunch-menu) with a single merged price and headers; a new link in the page index; a temporary style block |
index.html |
A table of weekly opening hours by service in #opening-hours, with a two-level head, grouped days, caption and scope (still unstyled) |
| Other pages | No changes |
Common Mistakes and Tips
- Going back to presentational attributes (
border,cellpadding,bgcolor,align) because "it's quicker": all of that is CSS. - Forgetting
border-collapse: collapse: double lines and gaps between cells appear. - Aligning numbers to the left or the centre: it makes them harder to compare. Figures and prices go on the right (and so does their header).
- Trying to align text or change the font with
col: it only accepts background, width, border and visibility. For everything else, use classes on the cells. - Zebra rows in opaque colours when you are also highlighting columns: they cover the column's background. Use semi-transparent colours.
- Low contrast between the text and the background of the head or the rows: what looks elegant on your screen may be illegible on another one or for people with low vision.
- Typing the content in capitals to make it look that way: use
text-transform. - Leaving styles scattered in the
styleattributes of each cell: astyleblock (and, from Module 8, the external stylesheet) keeps the appearance in a single place. - Tip: a useful touch on long tables is to highlight the row under the mouse pointer with
tbody tr:hover { background-color: #fff2c2; }. Try it: you will study the:hoverpseudo-class in Module 8.
Exercises
Exercise 1. Convert this old table into HTML5 with no presentational attributes, with a style block that achieves the same look:
<table border="1" cellpadding="6" cellspacing="0" width="400">
<tr bgcolor="#1f4e79">
<th align="left"><font color="white">Coffee</font></th>
<th align="right"><font color="white">Price</font></th>
</tr>
<tr>
<td>Colombia (250 g)</td>
<td align="right">€7.50</td>
</tr>
</table>Exercise 2. Bring the styles to the opening hours table in index.html: copy the menu's style block into the home page's head and add a rule so that the opening hours data cells (not the header cells) are centred, without affecting the footnote. Then answer: what is the problem with having copied the block into two pages?
Exercise 3. Write the CSS rule so that, on the menu, it's the odd rows of the body that get the zebra colour, and explain why, with several tbody elements, the result might not be what you expect.
Solutions
Solution 1.
<style>
table {
border-collapse: collapse;
width: 400px;
}
th, td {
border: 1px solid #000000;
padding: 6px;
text-align: left;
}
thead th {
background-color: #1f4e79;
color: #ffffff;
}
.price {
text-align: right;
}
</style>
<table>
<thead>
<tr>
<th scope="col">Coffee</th>
<th scope="col" class="price">Price</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Colombia (250 g)</th>
<td class="price">€7.50</td>
</tr>
</tbody>
</table>border="1"→borderon the cells;cellspacing="0"→border-collapse: collapse;cellpadding="6"→padding;width="400"→width;bgcolor→background-color;align→text-align(with thepriceclass).- The
fontelement is obsolete too: the text colour is set withcolorin CSS. - Along the way, the table gains structure:
thead,tbody,scopeand the coffee name as a row header. (If you turn thattdinto ath, remember that with this CSS it will be bold; you can remove that as on the menu.)
Solution 2. After copying the block into the head of index.html, add:
The tbody td selector only affects the data cells in the body: the th elements ("Counter", "Bread sales"…) stay on the left, and the footnote, which is in tfoot, doesn't change. Centred times sit well with the cells merged across several days.
The problem with copying the block: the same CSS is now duplicated. If you change the blue of the head, you will have to change it in two files, and it's easy for them to end up different. What's more, this new rule only exists in index.html; if the menu had another timetable, it wouldn't have it. The solution is a single css/styles.css stylesheet linked from every page, which you will create in Module 8.
Solution 3.
The position is counted within each tbody, and in each group the first row (odd) is the category row, whose th has its own background and covers the row's. That's why the first product in each group (2nd row) has no colour, the second (3rd) is coloured, and so on. If one group has an odd number of products and the next starts afresh, the pattern "restarts" in each category. This is usually desirable, because each group is read separately, but it's worth knowing so that it doesn't take you by surprise.
Conclusion
With this lesson you complete the Tables in HTML module. You have learnt to give a table a professional look with CSS: border-collapse for a clean grid, padding to give the cells room to breathe, text-align with numbers on the right, zebra rows with :nth-child, styles for the head, the groups and the foot that rely on the structure itself, col for highlighting columns (with its limitations), caption-side and control over the width; and you have left behind obsolete attributes such as border, bgcolor and cellpadding. Over the course of the module, The Blue Cup has gone from prices written in lists to a menu in a table with sizes, allergens, categories and a footnote, a lunch menu with a single price and weekly opening hours by service, all accessible to screen readers. Tables display information; now it's time to collect it. If you open bookings.html, it still says "Very soon you will be able to book online from this page." In the next module, Forms in HTML, you will start with the lesson Creating a Basic Form and keep that promise: customers will be able to book a table (or a place on the bread-making workshop) directly from the website.
HTML Course
Module 1: Introduction to HTML
- What Is HTML?
- Setting Up Your Work Environment
- Basic Structure of an HTML Document
- Tags, Elements and Attributes
- Creating Your First HTML Page
- File Organisation and Paths
Module 2: Text Formatting in HTML
- Headings and Paragraphs
- Text Formatting Tags
- Lists: Ordered, Unordered and Description Lists
- Block Quotes and Preformatted Text
- Block and Inline Elements: div and span
Module 3: Links and Media in HTML
- Creating Hyperlinks
- Special Links: Anchors, Email, Phone and Downloads
- Adding Images
- Embedding Videos
- Using the Audio Element
Module 4: Tables in HTML
- Basic Table Structure
- Table Head, Body and Foot
- Merging Cells: colspan and rowspan
- Accessible Tables: caption, scope and headers
- Styling Tables
Module 5: Forms in HTML
- Creating a Basic Form
- Form Elements: input, textarea and select
- HTML5 Input Types
- Labels and Grouping: label, fieldset, legend and datalist
- Form Attributes and Validation
- Submitting Forms
Module 6: HTML5 Semantic Elements
- Introduction to Semantic HTML
- header, nav and footer
- article, section and aside
- main and figure
- Other Semantic Elements: time, address, details and dialog
Module 7: Advanced HTML Techniques
- HTML Entities
- Using iframes
- Data Attributes
- Metadata: meta, SEO and Open Graph
- Microdata and Structured Data
- Graphics in HTML: SVG and canvas
Module 8: Integrating HTML and CSS
- Linking CSS to HTML
- Inline, Internal and External CSS
- Basic CSS Selectors
- The Box Model
- Styling HTML Elements
- Introduction to Layout with Flexbox and Grid
Module 9: Responsive Web Design
Module 10: Best Practices and Accessibility
- HTML Best Practices
- Validating HTML Code
- Web Accessibility Basics
- Using ARIA Roles and Attributes
- Accessibility Testing
- Performance and Resource Loading
