How to create responsive table in modern way
Table is an important tool for representing data, however, for small screens e.g. mobile and tablet, it is also crucial to represent data in different way. Otherwise, it turns into chaos!
New friend: Flexbox
For modern browsers, we all can use flexbox to create responsive tables! If you want to know more about flexbox, you can always view the superb guide from CSSTricks!
First, this is what we want to do:
Don’t care about the tours right now, it just copy and paste from the web (although I also hope to go there lol)!
First, we can create the structure of the table. The most tricky one is the nested table in “United States”, we will use nested div to cover that:
For simplicity purpose, we use Flag Icon CSS to create flags here. For production, it should use SVG or SVG sprites to do so, as we only need few flags (to save more bandwidth!).
For nested table of “United States”, you can see we used different class column to create it.
Then, our lovely CSS!
For normal rows, we use .flex-table and .flex-row to wrap them, and the rows are equally 25%, which means 100% / 4.
For nested rows, the first cell is 25%, then we use .column as the container, width 75% and wrap tables with .rowspan and .flex-table .
The most important one is box-sizing:
So that all paddings, borders etc. will not count in 100%. If you have not use this code and you added 0.5em padding, you will need to calculate the width yourself, e.g. calc((100% — 0.5em) /4) in your CSS.
The 2nd important one is flexbox layout!
As you can see, we use flexbox for this layout, and all cells are in a row, so we need to add this code to .flex-table .
Flex-flow is the shorthand for flex, the first row is flex-direction, which means all cells become rows automatically.
The second one is flex-wrap, so if all elements exceed width of container, it will automatically wrapped to second line.
Last but not least, the border settings are important too!
Since div’s border will overlap, so all the borders should be unique. This time, I have set the bottom and right border in .flex-row and left border in .flex-table . So the bottom border will create top border for the next row 🙂
Here comes our final product:
Newcomer: Grid layout
Not all the browsers can use this method, only 80% of browsers support it. But, why don’t we have a try? Let’s try to change the previous flexbox table to CSS grid layout!
First, delete all flexbox-related properties and add:
After added repeat(auto-fill, 25%) , it will automatically generate rows of 25%.
The most tricky one is the nested table in tablet version, which the first cell will changes to 100%. Do we need to create grid of 100% this time? No, we will create 33.33%, that means 3 cells in 1 row.
What does that means? That means when a div has .first class, which is the first cell, it will occupied 1–3 grid.
That means, when we created 33.33% * 3 grid in 1 row, the first cell will occupied 1 full row. Then the next row starts, all the remained items will go to next row.
Here comes our final results!
How about accessibility?
Well, using div to create table is neither native nor semantic. The best way to create table is still using the native <table> tag. You still can use the div method, but don’t forget the aria-labels!
If you want to achieve that using native method, here comes the responsive version:
Just like back to 1990s! But you can see that, less HTML and CSS to get the same result, and save more time for both accessibility (Explore more about accessibility here) and development.
What would you choose to create your fancy responsive table these days? Welcome to express your opinions!
Верстка таблицы (SCSS + flexbox)

Иногда на макетах встречаются сложные блоки, когда не совсем понятно, как их верстать. Сегодня мы сверстаем один из таких блоков — «Преимущества». Присмотревшись внимательно, вы заметите, что текст лежит в ячейках. Сквозь дизайн явно проступает табличная структура, только хорошо замаскированная.
Верстальщики очень не любят делать верстку таблиц, из-за сложностей получить адаптивность. Однако в нашем случае все не так страшно, поскольку в этой таблице мало контента и нам не нужно будет её перестраивать.
HTML структура
Визуально секция делится на две части: таблица (слева) и отдельный блок (справа). Обе части являются flex-элементами и находятся в общем flex-контейнере advantage.

.advantage <
display: flex;
justify-content: space-between;
>
В свою очередь флексовый контейнер находится внутри внешнего контейнера container и секции section.
В секции задаются внутренние отступы.
.section <
padding: 100px 0;
>
Внешний контейнер ограничивает всю конcтрукцию по ширине и выравнивает по центру страницы.
.container <
max-width: 960px;
margin: 0 auto;
>
Верстка таблицы (HTML код)

Верстка таблицы (SCSS код)
.advantage <
display: flex;
justify-content: space-between;
Верстка адаптивной таблицы
Теперь на ширине экран меньшей, чем 992 пикселя, главная ось поменяет своё направление на вертикальное. В результате таблица и блок с пользователями перестроятся на колонки. Сама таблица будет сжиматься по мере уменьшения ширины экрана.

@media only screen and (max-width: 992px) <
.container <
max-width: 720px;
>
.advantage <
flex-direction: column; // главная ось поменяла направление
align-items: center;
>
.advantage-table <
margin-bottom: 60px;
>
.advantage-users <
height: 290px;
align-self: center;
>
>
@media only screen and (max-width: 576px) <
.advantage-table <
font-size: 10px;
margin-bottom: 40px;
>
>

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Она выглядит вот так:
Комментарии ( 0 ):
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Как сделать таблицу с помощью flex
Где изначально расположение ячеек на узких экранах будет см отрется спасительно, но совершенно в другой форме, а точнее вертикальной, хотя по умолчанию на широком мониторе мы наблюдаем горизонтальное положение.
Это универсальный материал, что отлично подойдет для любого объема текста.
При открытие на большом размере монитора:
Здесь уже наблюдаем с мобильного гаджет:

Обратите внимание, что заголовок таблицы дублируется, это происходит в каждой ячейки в теге span. Все сделано для того, чтоб все отлично отображалось на узких экранах.
Really Responsive Tables using CSS3 Flexbox
For a long time, I've been looking for a really responsive way to handle tables in a browser. Some technique that lets tables smoothly adapt to many screen sizes, not just desktop vs. mobile. Having found none, I created my own using <div> s and CSS3 Flexbox, and here it is.
Why tables
- Tables are a very nice way to show a list of very similar items. People just get it, when it's a table.
- The alignment of fields in columns is very helpful in getting a feel for the values, how they differ or are similar across rows.
- Using cards like this list of JIRA issues is an option, still, it doesn't feel as good as a table when the number of rows / columns is large such as this bugzilla bug list.
Problems with conventional tables
- If they are fixed width, they don't let the user take advantage of a larger screen size.
- If they are not fixed width, cells can wrap on smaller screens. But only cells with long content wrap, and you can get uneven sized rows. This is an eyesore.
- If you set overflow: hidden and add ellipsis to restrict all rows to one line, on very small screens, you end up seeing almost nothing.
There are many solutions proposed for responsive tables at this post: 10+ Solutions for Responsive Data Tables. But I'm not happy. They're all binary solutions (i.e., Desktop vs. Mobile — all or none). There are no solutions that address what I really want, something smoothly adapting to varying screen widths — really responsive.
What I want: really responsive tables
- Maximisation of real-estate is important. Minimum white space.
- Wrapping cells is not OK. Wrapping a row is ok, as long as all rows are laid out the same way.
- No horizontal scrollbar, ever.
- Fields should be aligned, otherwise, it's not a table.
- Optimum layout for any screen size, that is, really responsive!
Flexbox to the rescue
I got enamored by CSS Flexbox, since it was faintly reminiscent of GridBagLayout (no, don't go there). This was my first exposure to fluid layouts, circa 1996.
If you are not familiar with Flexbox, please read A Visual Guide to CSS3 Flexbox Properties or this answer by @fazlerocks . It's is a pre-requisite to follow the rest of this story.
OK, now that you're familiar with Flexbox, we can discuss a few approaches to achieve really responsive tables using Flexbox <div> s instead of HTML <table> s. Let's start with a table which looks like this on large screens:

Plain Wrap
This is a simplistic approach using flex: wrap . When there isn't enough horizontal space, a row wraps naturally. The right most columns go to the next line, one after the other.

The CodePen for this approach is at Responsive Tables using Flexbox (Plain Wrap). Do play with it, check out its behaviour at various screen sizes.
Nested Wrap
Although the Plain Wrap approach is very simple to implement, the columns visually interfere with one another vertically. To address this, we nest multiple div s so that related cells stay together. The border colors show the nesting below.

Controlled Wrap
We still don't have control on which cells wrap when. Some times they look good, some other times, fields still interfere. I'd have really liked to see First Name and Last Name vertically stacked when displaying a row as two lines. This is because flex: wrap has its own mind and decides when to wrap what.
To have exact control we need to switch to flex-direction: column on the wrappers, whenever we want. To achieve this, we need media queries that change the flex-direction as the screen size shrinks.

For the same screen width as the previous example, this looks much better. Note that now we even have the numeric columns right-aligned, and they look good too!
Advanced Example
Controlled Wrap gives us what we want, but we made some big assumptions about uniformity of field widths. Life is usually not this simple. In reality, we encounter different field widths, some with fixed width, some variable. We have to deal with each column individually and lay it out to perfection, maybe like this:
Single line: 
3-line rows: 
5-line rows: 
Really responsive, finally.
To implement something on your own like this, it's a bit of a work, especially to decide how the columns are laid out at different screen sizes. But, believe me, it's worth it.

