Is it possible to let the table split into more columns according to its container's width?

Viewed 27

I have a very long table (more than 100 rows).

When the container is wide (on a big external monitor), I hope it will take advantage of the wide space as follows:

enter image description here

When the container is narrow (on a mobile), I hope it just looks like this:

enter image description here

Is this possible with HTML and CSS?

2 Answers

If you can alter the HTML from a table to simple divs you could set it as a grid with break points for different viewport widths.

We need four (or how ever many the maximum you require is) copies of the column headings built in to the HTML.

This snippet has 4 breakpoints and obviously you'll want to put in the values you actually need.

.table {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

.table :nth-child(4),
.table :nth-child(5),
.table :nth-child(6),
.table :nth-child(7),
.table :nth-child(8),
.table :nth-child(9),
.table :nth-child(10),
.table :nth-child(11),
.table :nth-child(12) {
  display: none;
}

@media (min-width: 768px) {
  .table {
    grid-template-columns: repeat(6, 1fr);
  }
  .table :nth-child(4),
  .table :nth-child(5),
  .table :nth-child(6) {
    display: block;
  }
}

@media (min-width: 1024px) {
  .table {
    grid-template-columns: repeat(9, 1fr);
  }
  .table :nth-child(7),
  .table :nth-child(8),
  .table :nth-child(9) {
    display: block;
  }
}

@media (min-width: 1500px) {
  .table {
    grid-template-columns: repeat(12, 1fr);
  }
  .table :nth-child(10),
  .table :nth-child(11),
  .table :nth-child(12) {
    display: block;
  }
}
<meta name="viewport" content="width=device-width, initial-scale=1" />
<div class="table">
  <div>item</div>
  <div>Value A</div>
  <div>Value B</div>
  <div>item</div>
  <div>Value A</div>
  <div>Value B</div>
  <div>item</div>
  <div>Value A</div>
  <div>Value B</div>
  <div>item</div>
  <div>Value A</div>
  <div>Value B</div>
  <div>iii</div>
  <div>aaa</div>
  <div>bbb</div>
  <div>iii</div>
  <div>aaa</div>
  <div>bbb</div>
  <div>iii</div>
  <div>aaa</div>
  <div>bbb</div>
  <div>iii</div>
  <div>aaa</div>
  <div>bbb</div>
  <div>iii</div>
  <div>aaa</div>
  <div>bbb</div>
  <div>iii</div>
  <div>aaa</div>
  <div>bbb</div>
  <div>iii</div>
  <div>aaa</div>
  <div>bbb</div>
  <div>iii</div>
  <div>aaa</div>
  <div>bbb</div>
</div>

It is always difficult to handle table in a responsive way. I normally target mine to the smallest size.

Since you want to keep the semantic structure and still split the table, I think you need to do this manually.

I suggest that you provide 2 or 3 different formats of the table and let the user select one. Maybe provide two buttons + and -. Or provide a dropdown to select a format/size.

Related