Allowing elements to scroll inside a browser viewport is generally a bad design decision: users are likely to confuse the scrollbars on the inner element and the browser viewport, slowing speed and usability.
However there are rare occasions when scrolling might be considered for HTML elements. One such scenario is a shopping table, in which products or services with small but important distinctions are presented in rows.
In a future article, I’ll show you how to use JQuery to “stick” ; rows in the table, allowing easy comparison between products. In this section, I’ll present the markup and CSS for the table.
The code is fairly straightforward: a table header section (<thead>
) with column headings, table body (<tbody>
) containing the table data (different computer processors, in this case) and a table footer (<tfoot>
). Rather oddly, the table footer is placed before the body in the code, but automatically appears underneath it in the browser. In this example, there is no data in the table footer, and its role is purely presentational.
<table>
<thead>
<tr>
<th>Package
<th>Manufacturer
<th>Name
<th>Speed
<th>Cores
<th>Cache
<th>Price
<tfoot>
<tr>
<td colspan=6>
<tbody>
<tr>
<td><img src=amd-opteron.jpg alt="AMD Opteron 6172 Twelve-Core 2.1GHz">
<td>AMD
<td>Opteron 6172
<td>2.1 GHz
<td>12
<td>18 MB
<td>$1,199.99
<tr>
<td><img src=i7-3960X.jpg alt="Intel Core i7-3960X Processor">
<td>Intel
<td>Core i7-3960X
<td>3.3 GHz
<td>6
<td>15 MB
<td>$1,049.99
…
</table>
The table header and footer both contain vertical gradients, white to transparent (reversed in the footer). The secret to getting the <tbody>
element to scroll vertically is fourfold:
- Set the
<tbody>
todisplay: block;
- Constrain it to a specific
height
; - Set
overflow
toauto
; - Hide the excess with
overflow-x
The complete CSS code, albeit without vendor prefixes for the linear gradients:
table {
border-collapse: collapse;
box-sizing: border-box;
}
td img {
width: 100px;
height: 100px;
}
table, thead, tbody {
display: block;
position: relative;
}
thead, tbody, tfoot {
width: 700px;
}
th, td {
padding: 1.2rem;
}
thead {
background-image:
linear-gradient(rgba(255,255,255,1) 70%,
rgba(255,255,255,0));
z-index: 2;
}
tbody {
height: 270px;
overflow: auto;
overflow-x: hidden;
margin-top: -20px;
}
tfoot {
background:
linear-gradient(rgba(255,255,255,0) 30%,
rgba(255,255,255,1));
position: absolute;
bottom: 0;
height: 20px;
z-index: 3;
}
The <tbody>
is also given relative
position in order to raise it under the table header element; the footer is absolute
so that it can be placed on top of the tbody
.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.