CSS: tables (reformat) // Mash
Выдержка из спецификации CSS2 (Appendix A. A sample style sheet for HTML 4.0):
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 }
Приложение не является нормативным, а носит только информативный характер. Разработчикам желательно использовать этот пример в качестве таблицы стилей, применяемой по умолчанию.
Так отображаются таблицы «по дефолту». <table> — таблица; <tr> — строка ячеек; <th>, <td> — ячейка таблицы т.д. То, что вы видите ниже, — обычная таблица, состоящая из <table>, <thead>, <tbody>, <th>, <tr> и <td>. Ничего лишнего.
Nmb. | Picture | Title | Author | Description (from Amazon.com) | Cost |
---|---|---|---|---|---|
1 | ![]() | Designing With Web Standards | Jeffrey Zeldman | If ever there were an author who could make web standards exciting, it's Jeffrey Zeldman. His light and humorous writing style make for such an engaging read. It's only after you stop reading that you realize how much you're learning. What's more, you're not just learning —… Read more | $... |
2 | ![]() | Don't Make Me Think | Steve Krug | Usability design is one of the most important—yet often least attractive—tasks for a Web developer. In Don't Make Me Think, author Steve Krug lightens up the subject with good humor and excellent, to-the-point examples… Read more | $... |
3 | ![]() | CSS Pocket Reference | Eric A. Meyer | CSS (Cascading Style Sheets) is the W3C-approved method for enriching the visual presentation of web pages. CSS allows web pages to become more structural, and at the same time promises that they can have a more sophisticated look than ever before. With good implementations in Internet Explorer… Read more | $... |
Попробуем изменить значения свойства display
для элементов этой таблицы:
table, tbody, tr, td {display: block;}
thead {display: none;}
Вот что может получиться, если добавить оформления к этим блокам (работает в Mozilla 1.4+ и Opera 7.0; для сохранения хорошего состояния пищеварительной системы пользователей IE пример от них скрыт):
It does not work in Windows Internet Explorer.
Nmb. | Picture | Title | Author | Description (from Amazon.com) | Cost |
---|---|---|---|---|---|
1 | ![]() | Designing With Web Standards | Jeffrey Zeldman | If ever there were an author who could make web standards exciting, it's Jeffrey Zeldman. His light and humorous writing style make for such an engaging read. It's only after you stop reading that you realize how much you're learning. What's more, you're not just learning —… Read more | $... |
2 | ![]() | Don't Make Me Think | Steve Krug | Usability design is one of the most important—yet often least attractive—tasks for a Web developer. In Don't Make Me Think, author Steve Krug lightens up the subject with good humor and excellent, to-the-point examples… Read more | $... |
3 | ![]() | CSS Pocket Reference | Eric A. Meyer | CSS (Cascading Style Sheets) is the W3C-approved method for enriching the visual presentation of web pages. CSS allows web pages to become more structural, and at the same time promises that they can have a more sophisticated look than ever before. With good implementations in Internet Explorer… Read more | $... |
А вот ещё два примера: «Reformat the Table» by Seamus P. H. Leahy (example 1, example 2).
Здесь интересны три момента:
- «обход» ячеек таблицы псевдо-классом
:first-child
(первый дочерний элемент своего родительского элемента) и смежными селекторами типаtd + td
. Например, размер шрифта содержимого всех четвёртых ячеек строк таблицы задаётся равным 90% следующей конструкцией:
Т.е. для элементаbody table#extable tr td:first-child + td + td + td{ font-size: 90%; }
td
, которому предшествуют три элементаtd
, а первый из них является первым дочерним элементом по отношению к элементуtr
таблицы с атрибутомid="extable"
, значение свойстваfont-size
устанавливается равным 90% (уффффффф…). Согласитесь, что это гораздо лучше, чем присваивать классы ячейкам таблицы, засоряя HTML:
Не стоит забывать, что CSS падает в кэш клиенту (в общем случае) и кушать не просит.<tr> <td class="nomber">1</td> <td class="picture"><img ... /></td> <td class="title">Title Of Item</td> <td class="author">Author</td> <td class="description">Description</td> <td class="cost">Money</td> </tr>
- использование псевдоэлементов
:before
и:after
для вставки генерируемого содержимого:body table#extable tr td:first-child + td + td:before{ content: "Title: \00AB"; } body table#extable tr td:first-child + td + td:after{ content: "\00BB"; }
- использование селекторов, синтаксис которых не понимает Internet Explorer (
html>body
, etc.). Задавая желаемые свойства элементов таблицы посредством таких селекторов можно добиться того, что пользователи IE увидят табличные данные в «классическом» варианте, а пользователи браузеров с поддержкой CSS в более полном объёме… полёт человеческой мысли, ага.
7 сентября 2003