Styling HTML tables
This article provides a guide to the fundamental styling options available for tables.
Introduction
At times it seems that tables are a little misunderstood in modern web development. So much attention is given to “don’t use tables!” that people sometimes forget the issue is actually "don’t use tables for layout". Tables are excellent for their true purpose — displaying tabular data. So it makes sense to know how to style them properly.
This article focuses on applying CSS in an efficient manner, to produce clear and readable data table styles. We’ll also cover some common design requests for tables.
Table structure
Before we dive into the CSS, let’s consider the key structural elements of tables you will need to style clearly:
- Table headings
- Table data cells
- Table captions
When your site users read your table, they should be able to easily understand and follow the structure of the table. The most common way to do this is with borders, background colours, or both.
You do not have to follow these style conventions, however, you should ensure that there is some clear difference between th and td cells; also, the caption should be clearly associated with the table and differentiated from other text on the page.
The basics
Consider the way this unstyled table is rendered (this is the same example you met in HTML tables):
| Volcano Name | Location | Last Major Eruption | Type of Eruption |
|---|---|---|---|
| Compiled in 2008 by Ms Jen | |||
| Mt. Lassen | California | 1914-17 | Explosive Eruption |
| Mt. Hood | Oregon | 1790s | Pyroclastic flows and Mudflows |
| Mt. St. Helens | Washington | 1980 | Explosive Eruption |
The data is understandable, but it does takes some effort to work out what’s happening. Let’s add some style to make it easier to read.
Table and cell width
The first decision is how wide to make the table. The browser default is the same as setting table < width: auto; >, which results in the table extending to the width of the content. This generally looks untidy.
Let’s imagine that our table is going into a content column 600px wide. Let’s set the table to expand to 100% of the available width, to make best use of space. Since there are four columns, let’s also set the width of the table cells to an equal 25% each:
You can actually just set the width on th and it will set the width of all the columns; however, it doesn’t hurt to be thorough. This simple style will produce the result seen in Figure 1:
Figure 1: The example table with simple width settings.
The cells are now sitting at an even width. We’ll look at setting uneven widths later, but for now let’s push on.
Text alignment
The table is still a bit confusing to read, so let’s set up the text alignment to be a little neater — the additional rule below will left-align the headers to match the content (by default, browsers centre table headings):
This neatens things up a little, as you can see in Figure 2:
Figure 2: Table with left alignment applied.
Currently all of the cells are vertically aligned to the centre. If you prefer, you can set this to align text to the top or bottom of the cell, or in fact any vertical-align setting that you like. The new rules below set the text to align to the top:
The table now looks like Figure 3:
Figure 3: Table with vertical alignment added.
Note how the top row of headings all sit at the top, even though “Last Major Eruption” wraps on to two lines.
Borders
The table is looking a little nicer, however it is still a bit hard to read along each line. It’s time to set some borders to make things easier to read. You need to set borders separately for each part of the table, then decide how those borders should combine.
To show where the borders will be set, Figure 4a shows different borders for table ( solid black ), caption ( solid grey ), th ( dashed blue ) and td ( dotted red ):
Figure 4a: illustration of the different element borders within a table.
Note how the table border runs around the outside of all the heading and data cells, then between the cells and the caption. You can also see that by default, the th and td borders are spaced out from each other.
Let’s look at a different style of table — you can set up a simple black border for the table and cells, using the border property — this is done via the new rules below:
Which produces the result seen in Figure 4b:
Figure 4b: Table with simple black borders applied.
This makes the rows far easier to read, however you may not like the spacing between the cells. There are two ways to change this.
First, you can simply close the gaps using the border-spacing property, like so:
This will make the borders touch together instead of sitting apart. This changes the 1px border into a 2px border, as seen in Figure 5:
Figure 5: Table with border spacing removed, producing a 2px border effect.
You can also increase the space between cells using border-spacing , although bear in mind that this property doesn’t work in Internet Explorer.
If you want to retain the 1px border effect, you’ll need to set the table so that the borders “collapse” into each other. You can do this using the border-collapse property instead of the border-spacing property:
This will produce a table with a 1px border, like in Figure 6:
Figure 6: Table with border-collapse set to collapse, reducing the border to 1px.
When you set borders to collapse, you need to keep in mind that this can cause issues if you have different border styles applied to adjacent cells. When the different border styles are collapsed into each other, they will “conflict” with each other. This is resolved according to the W3C CSS2 Table border conflict resolution rules, which determine which style “wins” when they are collapsed.
Padding
Now that you have borders on the cells, you might like to add some whitespace to the caption and table cells. You simply use padding to accomplish this:
This allows the text to “breathe” a little, as seen in Figure 7:
Figure 7: Table with padding applied to all cells.
Caption placement
So far the caption has been left sitting at the top of the table. However, you might like to move the caption somewhere else. Unfortunately you cannot do this in IE, but for all other browsers you can change the position of the caption using the caption-side property. The options are top, bottom, left and right. Let’s move the caption to the bottom:
Figure 8 shows the result.
Figure 8: Table with caption moved to the bottom of the table.
If you do want move the caption, remember that any side-specific styles will not work in IE. For example if you add three borders to make the caption “join” the bottom of the table, it won’t have the desired effect in IE because the caption will still be at the top. You will need to use conditional comments to re-style your table for IE. See also the Fixing IE with conditional styles specification section for more details.
For the rest of the examples, we will leave it at the top.
Backgrounds
Another simple way to style tables is to add background colours and images. This is done with the background property, although you need to be aware that the different parts of the table will “layer” over each other. The CSS2 specification explains background layering in some detail however the short version is that backgrounds will override each other in the following order:
- table (which sits at the “bottom” or the “back”)
- column groups
- columns
- row groups
- rows
- cells (“top” or "front", meaning their background overrides all the others)
So, if you set a background for the table, and a different colour for cells, the cell background will cover up the table background. If you have borders set to collapse , the table background won’t show at all. If you set border-collapse to separate , however, the table background will show through between the borders.
Note that the concept of different elements sitting on top of one another on the page is controllable; you can control how high or low in the stack an element sits in relation to other elements by changing its z-index property.
Imagine you set the table to have a red background and cells to have a white background. Separated cells will show the red, but the cells stay white, as demonstrated by Figure 9:
Figure 9: Table demonstrating the red table element background showing between the white backgrounds of the cell elements.
You can also use a background image. For example, if you wanted to have a gradient showing through between the cells, you could set the th and td cells to white backgrounds, but set the table background to a gradient:
Note that the background colour is set to black, which will fill up the space at the top where the gradient graphic finishes (you should always allow for your table being taller than the background image). The foreground colour is set to white, in case these default colours ever show through to the cell content. In general, the cell styles will override the text colour settings from the table <> style, but you should always declare contrasting foreground and background colours at each level.
These styles produce a table which would look like Figure 10 in most browsers:
Figure 10: Table demonstrating a gradient background image showing through between the cells.
By default IE won’t show as much of the background, since it doesn’t support border-spacing . However you will still get the same general effect, as indicated by Figure 11.
Figure 11: The smaller border-spacing gap rendered by IE.
Depending on your circumstances, you may be happy to simply accept this different rendering between browsers. Of course that isn’t always an option, for example when a client particularly wants a design to look exactly the same in all browsers.
Fixing IE with conditional styles
There is a workaround for the IE problems listed above. It requires a hack and an extra stylesheet, but it works. You can use an expression to produce the wider gap, then load that expression using conditional comments. The expression syntax is:
This CSS is only useful to IE, so you only want IE to apply it. The expression will also invalidate your stylesheet, so many developers prefer to isolate IE hacks in a separate stylesheet only loaded by IE.
To do this, create a new stylesheet named ie-only.css and link it within conditional comments:
Note the [if lte IE 7] means "if less than or equal to IE version 7". This reveals the code to IE7 and all earlier versions of IE, while the surrounding HTML comment hides the code from all other browsers. You can adjust this to whichever version of IE you need to target, for example to target IE6 and earlier use [if IE 6] .
In your main stylesheet, set the normal style:
Then set your IE-only style in ie-only.css :
This will get IE to produce a table with wide cell spacing. You just have to remember to maintain the extra width settings — if you update your main stylesheet, you will have to update ie-only.css as well. Obviously conditional comments allow you to do a lot more than just style tables, since the extra stylesheet can contain as much CSS as you need to fix IE bugs.
A simple design
Most designs use relatively simple combinations of backgrounds. Let’s give the table headers a grey background, and change the caption to be white text on black:
This looks like Figure 12:
Figure 12: Table with reversed white-on-black caption and light grey background applied to the table heading cells.
Common variations
In this section I will look at some common design archetypes you will see again and again in tables across the Web.
Zebra striping
A common design request for tables is to create rows with alternating colours. These are commonly referred to as "zebra striping". Although there is some conjecture as to whether zebra striping actually helps the reader, they are a popular style. Figure 13 shows an example:
Figure 13: A table with "zebra stripes", alternate rows set to white or light grey.
The simplest way to accomplish zebra stripes is to add a class to alternate table rows, then use a contextual CSS selector to style the cells in those rows. First, the classes “odd” and “even” are added to the table rows, like so:
You can skip the heading row as it already has its own style. You then add a contextual class to set the background for all cells inside odd class rows:
This is the simplest way to add zebra striping to an HTML table that will work across all browsers, but it is not perfect — what if you add a row to the table? You’d then need to move all your odd and even class names around to get everything looking right again.
There are two other options:
- You can add the classes using unobtrusive JavaScript, as demonstrated in A List Apart: Zebra Tables. Most JavaScript frameworks have a suitable method, too: Zebra Table Showdown compares a range of framework implementations.
- You can use the CSS3 :nth-child selector, however, this isn’t supported across all the major browsers yet. Support will improve as time goes on though. You can find more out about zebra striping with nth-child in this dev.opera.com article.
Incomplete grids
Some designs will respond well to less structured, more open-looking grids. A simple variation is to remove the vertical borders and leave out the background fill on the caption, as seen in Figure 14:
Figure 14: A table with lighter grey borders only on the outer edge and bottom of each cell.
The CSS for this effect is:
You can take this a step further and remove all of the borders, except a top and bottom border to give some definition to the table body — see Figure 15:
Figure 15: A table with borders applied only to the top and bottom of the table body.
The CSS for this effect is:
Inner grids
Sometimes you will want to remove the outer border, but keep the inner grid of borders, like in Figure 16:
Figure 16: A table with an inner grid design.
To accomplish this for all current browsers, you need to add a class to the th and td cells that appear last on each row, like this:
Then we use that class to remove the right border from those cells. The full CSS is:
Inner grids using :last-child
When browser support improves, we will be able to use the pseudo selector :last-child to achieve this effect without classes. The CSS would be:
This currently works in the latest versions of Opera, Firefox and Safari.
Two common bugs
In this last section we’ll cover two really common bugs, so you’re prepared for when they crop up. They concern borders and captions.
border-collapse bug
When you set your table to border-collapse: collapse; you will find that Firefox and Safari will incorrectly display the width of table features. For example, if you set a 1px border on the table, cells and caption, Firefox will render the caption 1px too narrow on the left, as seen in Figure 17:
Figure 17: The border-collapse bug affects Firefox and Safari.
Safari does the same thing, just on the right. This bug is all based on a rounding issue that ultimately comes down to how you display "0.5 of a pixel". It can be argued that this is not a bug per se, but the browsers don’t agree, so it’s effectively a bug.
So what’s the solution? If you want to use a 1px border and a caption background, there really isn’t a fix other than to "live with it ". It is a very minor difference and a non-fatal problem — that is, the table remains entirely usable. So, many people choose to just live with the differences between browsers. Let the Web be the Web.
If you are happy to use a larger border, say 2px, then you can simply set a 1px border on table, cells and caption; then set table to separate borders and apply zero spacing between them:
In Firefox at least, the 1px borders will add up to the desired 2px rendered border, avoiding the rounding problem on the way. Safari still leaves a gap.
Alternatively, you can hide the problem by not using a border or background colour on your caption. The problem is still there; you just won’t see it. This is probably the simplest and most effective solution.
Margin/caption bug
If you use a caption and set a margin on table , you need to be aware that Firefox and Safari may place the table margin between the table cells and the caption.
To combat this in Firefox, you can set the margin on three sides of table , set the caption-side explicitly, then add the fourth margin to the caption . Unfortunately, this solution will invoke the bug in Safari. So, this isn’t really a fix unless you are willing to live with the bug in either Firefox or Safari.
The only way to avoid a problem in both Firefox and Safari is to set a zero margin on the side with the caption. For example, if your caption is at the top you could just set your margin on the right, bottom and left sides; or just the bottom. This may work if you set all of your margins on the same side of content elements, so the margin isn’t required to space the table from adjacent content.
Стилизация таблиц
Стилизация HTML таблиц это не самая гламурная работа в мире, но иногда нам нужно это делать. Эта статья руководство как сделать, чтобы ваши HTML таблицы выглядели хорошо, с некоторыми свойствами подробно рассмотренными в предыдущих статьях.
| Необходимые знания: | Базовый HTML (Введение в HTML), HTML таблицы (смотрите раздел HTML таблицы (TBD)), и представление о том как работает CSS (Введение в CSS). |
|---|---|
| Цель: | Научиться эффективно стилизовать HTML таблицы. |
Типичная HTML таблица
Давайте начнём с рассмотрения типичной HTML таблицы. Когда мы говорим о примерах типичных HTML таблиц обычно речь идёт о обуви, погоде или сотрудниках; мы решили сделать это более интересным создав таблицу о знаменитых панк группах Великобритании. Разметка выглядит следующим образом:
Таблица размечена, немного стилизована и понятна, благодаря использованию таких свойств как scope (en-US), <caption> , <thead> (en-US), <tbody> (en-US) и т.д. К сожалению при просмотре в браузере она не очень хорошо выглядит (посмотреть можно здесь punk-bands-unstyled.html):

Это выглядит достаточно грубо, трудно читаемо и скучно. Нам нужно использовать немного CSS чтобы все исправить.
Активное обучение: Стилизация таблицы
В этой части обучения мы будем работать над тем чтобы стилизовать наш пример таблицы.
- В начале необходимо сделать копию sample markup, загрузить оба изображения (noise и leopardskin), и вставить эти файлы в отдельную папку на вашем компьютере.
- Следующее, это создать новый файл style.css и сохранить его в той же папке вместе с другими файлами.
- Подключить CSS в HTML для этого разместить следующую строку в HTML внутри <head> :
Отступы и разметка
Первое что нам нужно это разобраться с отступами/разметкой, так как по умолчанию стилизация таблцы выглядит неразборчиво! Сделаем это, добавив CSS в ваш style.css файл:
Наиболее важные части следующие:
- Свойство table-layout (en-US) со значением fixed как правило полезно использовать для вашей таблицы, это делает поведение таблицы немного более предсказуемым, чем значение по умолчанию. Обычно столбцы таблицы имеют размер в зависимости от того сколько в них контента, что приводит иногда к некоторым странным результатам. Когда table-layout: fixed , размер ваших столбцов определяется шириной их заголовков и делает их контент соответствующего размера. Вот почему вы выбрали четыре разных заголовка с помощью селектора thead th:nth-child(n) ( :nth-child ) («Выберите n-ый дочерний элемент <th> (en-US) в последовательности, внутри элемента <thead> (en-US)«) и задать им заданную в процентах ширину. Ширина колонки соответствует ширине её заголовка, это правильное решение при определении размеров колонок таблицы. Крис Койер (Chris Coyier) более подробно рассматривает эту технику в статье Fixed Table Layouts. Мы также использовали width 100%, что означает, что таблица заполнит любой контейнер и будет отзывчивой (хотя для этого потребуется ещё некоторая работа для правильного отображения на экранах небольших размеров).
- Свойство border-collapse (en-US) со значением collapse это стандартная практика при стилизации любой таблицы. По умолчанию, когда вы задали рамки для элементов таблицы, все они будут иметь пробелы между собой, как показано на рисунке ниже:
Это не очень хорошо выглядит (хотя может это то что вам нужно, кто знает?). Если установить border-collapse: collapse; рамки схлопываются в одну и так выглядит намного лучше: 
- Мы установили border вокруг всей таблицы, это понадобится когда чуть позже мы будет устанавливать рамки вокруг header и footer таблицы — когда по периметру всей таблицы нет рамки и граница заканчивается просто отступом, таблица выглядит странно и разрозненно.
- Мы установили padding на элементах <th> (en-US) и <td> — это создаёт в талице воздух, который позволяет ей дышать, делая её более понятной.
На этом этапе наша таблица выглядит уже гораздо лучше:

Немного простой типографики
Теперь мы ещё кое-что изменим.
Во-первых, мы пойдём и найдём на Google Fonts шрифт который подходит в нашей ситуации с таблицей о панк группах. Вы можете можете выбрать для себя другой шрифт если захотят, тогда вам понадобится заменить представленный <link> элемент и изменить объявление font-family на выбранный вами Google Fonts шрифт.
Добавьте элемент <link> в блок head вашего HTML, на строчку выше существующего элемента <link> :
Затем добавьте следующий CSS в ваш style.css файл, ниже предыдущего кода:
Здесь нет ничего специально для таблиц, мы просто настраиваем стилизацию шрифтов, чтобы упростить чтение:
- Мы установили доступный глобально шрифт sans-serif; это вполне стандартный стилистический выбор. Мы установили выбранный нами шрифт для заголовков внутри элементов <thead> (en-US) и <tfoot> , который подходит нам по тематике панков.
- Мы добавили немного letter-spacing в заголовках и ячейках которым необходимо добавить читаемости. Опять же это основной стилистический приём.
- Мы выравниваем по центру текст ячейках внутри <tbody> (en-US) чтобы они совпадали с заголовками. По умолчанию у ячеек свойство text-align имеет значение left , а заголовки значение center , но обычно выглядит лучше если они выравниваются в одном стиле. По умолчанию, чтобы внешний вид заголовков отличался у них задан жирный шрифт.
- Мы выровняли заголовок справа внутри <tfoot> так чтобы он визуально ассоциировался с соответствующими ему данными.
В результате таблица выглядит немного аккуратнее:

Графика и цвета
И наконец-то графика и цвета! Наша таблица заполнена тем что имеет отношение к панкам, поэтому нам нужно придать ей яркий впечатляющий вид. Не беспокойтесь, вам не обязательно делать таблицу слишком кричащей — вы можете выбрать что-то более утончённое и со вкусом.
Следующий шаг это добавить следующий CSS в ваш style.css файл в самом низу:
Опять же здесь нет ничего конкретно для таблиц, но стоит отметить несколько вещей.
Мы добавили background-image в <thead> (en-US), <tfoot> и изменили color (en-US) для всего текста внутри header и footer на белый (и ещё text-shadow ) для лучшей читаемости. Вы должны всегда быть уверены что ваш текст хорошо контрастирует с фоном, для обеспечения читаемости.
Также мы добавили линейный градиент для <th> (en-US) и <td> элементов внутри header и footer для придания лёгкой приятной текстуры, а также установили этим элементам яркие пурпурные границы. Полезно иметь несколько вложенных элементов, это позволяет накладывать несколько стилей друг на друга. Да, мы могли бы установить и фоновое изображение, и линейный градиент на <thead> (en-US) и <tfoot> элементы используя множественные фоновые изображения, но мы решили сделать это отдельно для старых браузеров, которые не поддерживают несколько фоновых изображений и линейные градиенты (en-US) .
Полосатая зебра
Мы хотели бы посвятить целый раздел, чтобы показать вам как реализовать полосы зебры — чередующиеся цветные строки которые упрощают чтение разных строк в вашей таблице. Добавим следующий CSS в ваш style.css файл:
- Ранее вы видели как :nth-child селектор использовался для выбора специфичных дочерних элементов. В качестве параметра также может быть передана формула, тогда он будет выбирать последовательность элементов. Так формула 2n-1 выберет все нечётные дочерние элементы (1, 3, 5 и т.д.), а формула 2n выберет все чётные (2, 4, 6 и т.д.). Мы использовали в нашем коде ключевые слова odd и even , которые делают тоже самое что и формулы выше. В данном случае мы устанавливаем чётным и нечётным строкам разные (яркие) цвета.
- Ещё мы добавили повторяющийся плиткой фон ко всем строкам тела таблицы, который добавляет немного шума (полупрозрачный .png с небольшим количеством визуальных искажений на нем), чтобы получилась некоторая текстура.
- И наконец мы установили для таблицы сплошной цвет фона, который обеспечит фон строкам таблицы в том случае если браузер не поддерживает селектор :nth-child .
Этот взрыв цвета выглядит следующим образом:

То что получилось может быть не в вашем вкусе, но основная идея была в том, что мы попытались сделать таблицу которая не будет скучной и академической.
Стилизация заголовка
Последнее что мы сделаем с нашей таблицей это стилизация заголовка. Для этого добавим следующие строки в наш файл style.css :
Здесь нет ничего особенного, кроме свойства caption-side (en-US), которое имеет значение bottom . В этом случае заголовок будет размещён внизу таблицы и это вместе со всем остальным обеспечивает нашей таблице окончательный вид (можно посмотреть по ссылке punk-bands-complete.html):

Активное обучение: Стилизация вашей собственной таблицы
Теперь мы хотим, чтобы вы взяли наш пример таблицы (или использовали собственный!) и сделали что-то значительно более стильное и менее безвкусное чем наша таблица.
Стилизация таблицы быстрые советы
Короткий список наиболее полезных вещей рассмотренных выше:
- Сделайте свою разметку простой и гибкой, например, используя для этого проценты, что сделает дизайн более отзывчивым.
- Используйте table-layout (en-US) : fixed для более понятного поведения разметки, при этом легко установить ширину столбцов, установив ширину width для заголовков таблицы ( <th> (en-US)).
- Используйте border-collapse (en-US) : collapse , которое схлопнет границы элементов таблицы, что обеспечит аккуратный внешний вид.
- Используйте <thead> (en-US), <tbody> (en-US) и <tfoot> чтобы разбить вашу таблицу на логические фрагменты и предоставив таким образом дополнительные точки для применения CSS, это даёт возможность накладывать стили друг на друга, если это необходимо.
- Используйте полоски зебры, чтобы облегчить чтение между строк.
- Используйте text-align чтобы выровнять текст в <th> (en-US) и <td> для более аккуратного и удобного оформления.
Заключение
Несмотря на головокружительные успехи достигнутые в стилизации таблиц, у нас есть ещё кое-что чем мы можем занять наше время. В следующей главе мы рассмотрим некоторые продвинутые эффекты, уже устоявшиеся (например, тени box shadows) и те которые только недавно появились в браузерах, такие как режимы наложения blend-mode и фильтры.
Table CSS Creating beautiful HTML tables with CSS
It’s easy to make your HTML tables look great — in today’s post, we’re gonna take a look at around 30 lines of CSS to do just that!
Video Tutorial
Before I get into it, if you prefer this tutorial in video form, you may watch it on my YouTube channel, dcode, right below.
Writing the HTML
Let’s write some boilerplate HTML code for the table.
Exit fullscreen mode
Notice we have two classes:
- .styled-table so we don’t tamper with every <table> on the site
- .active-row which will be the «active» row — this class is used to highlight a specific row and will get it’s own CSS as we’ll see soon
Styling the table
Let’s target the main <table> element first:
Exit fullscreen mode
Most of these are self explanatory but let’s have a look at the main ones:
- box-shadow to add a subtle transparent shadow around the table
- border-collapse to ensure there is no space between the cell borders
Styling the header
For the header, we can simply change the background color and apply some basic styles to the text:
Exit fullscreen mode
Moving onto the table cells
Let’s space things out a bit:
Exit fullscreen mode
And the table rows.
For these, we want to do 3 things:
- Add a bottom border to each row for separation
- Add a lighter background to every second row to help readability
- Add a dark border to the very last row to signify the end of the table
Exit fullscreen mode
Lastly, let’s make the active row look different
For this, we’re just going to make changes to the text:
Exit fullscreen mode
And that’s it! If you have any suggestions for improvements please let me know in the replies below
Enrol Now JavaScript DOM Crash Course
If you’re learning web development, you can find a complete course on the JavaScript DOM at the link below
https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1

Top comments (21)
![]()
If you want your borders to look sharp on high resolution displays you can use thin instead of 1px 🙂
Update! This has apparently changed at some point and you only get regular 1px now (at least on iPhone).
![]()
Had no idea about this! Thanks
![]()
Nice, did not know about this! Will be using it for sure 🙂
![]()
![]()
Learn something new everyday!
![]()
Hmm, now that I paid attention to it this doesn’t seem to work anymore on iPhones 🙁
![]()
Yeah, your right! Thanks
![]()
I really love it. I’m bored of tons of bootstrap-like tables and your guide is such a refreshing approach
![]()
Appreciate that mate! Cheers
![]()
I agree with you! Bootstrap is all over the place (even tough i like it and use too)!

![]()
Hard to believe we once used tables to layout entire pages 🙂
Great example, was there any particular reason you used :nth-of-type instead of nth-child ?
I would be interested to know how you would make this responsive if you had a few more columns or where the data is a little longer.
CSS Tables
Some of the CSS properties are widely used to apply style on HTML tables. Each of them is described below.
In this chapter, we will talk about how to give styles to tables. We can change the color of headings and rows that we want.
Table Styling Properties
Here are CSS properties that we use for applying a style to the table. The background-color and color properties set the background color and the color of the text, respectively. The border-collapse property makes the table borders collapse. The text-align property sets the text position. Also, we should use the height, width and padding properties for styling.
Example of styling a table:
Result

Let’s explain the above code.
As you see our table has 2 parts: the first is the part where we have written headings, which is our <thead> part and the second part is the <tbody> part where we have written some text. The table has black borders, for which we use border property. We can use any color we want as well as we can choose the style of borders.
Table color
As you see the <thead> part of our table is blue and wherever we write some text is in white. For the blue background, we use the background-color property, and for the white text, we use the color property. The other texts are written with black.
Collapse Borders
The border-collapse property specifies whether the borders of a table are collapsed into a single border or separated.
Table Width and Height
The table also has width and height properties. As you see we use these properties in our style. We use the width property for the whole table and the height property for the headings. We can use these properties with pixels and percents.
Table Text Alignment
Now about the table text alignment. As you know earlier we used the text-align property for the text position. In our example, as you see, we use the text-align property for the heading. For that, we use «text-align: center». You can read our previous chapter to know how to use it.
Table Padding
To control the space between the border and content in a table, use the padding property on <td> and <th> elements:
Horizontal alignment with the text-align property
With the help of the CSS text-align property, you can set the horizontal alignment of the content in <th> or <td>.
By default, the content of <td> elements are aligned to the left and the content of the <th> elements are aligned to the center. In the example below, the content of <th> and <td> elements is aligned to the right:
Example of aligning the content of <th> and <td> elements to the right:
Vertical alignment with the vertical align-property
Using the CSS vertical-align property, you can set the vertical alignment of the content in <th> or <td>.
By default, the content in both <th> and <td> elements is vertically aligned to middle.
In the example below, the content of <td> elements is vertically aligned to bottom:
Example of the vertical alignment of <td> elements’ content to bottom:
Horizontal dividers
By adding the CSS border-bottom property to <td> and <th> elements, you will create horizontal dividers.
Example of creating horizontal dividers:
Hoverable tables
Using the CSS :hover selector on <tr> element, will make the table hoverable.
Example of creating a hoverable table:
Zebra-striped table
Using the nth-child() selector and adding the CSS background-color property to the odd (even) table rows, you can create a zebra-striped table.
Example of creating a zebra striped table:
Responsive tables
Adding any container element with the «auto» value of the CSS overflow-x property to the <table> element, you can make the table responsive.