Horizontal scroll on overflow of table

后端 未结 6 1808
耶瑟儿~
耶瑟儿~ 2021-01-30 12:31

I have a basic table in a container. The table will have about 25 columns. I am trying to add a horizontal scroll bar on overflow of the table and am having a really tough time.

6条回答
  •  孤城傲影
    2021-01-30 13:09

    The solution for those who cannot or do not want to wrap the table in a div (e.g. if the HTML is generated from Markdown) but still want to have scrollbars:

    table {
      display: block;
      max-width: -moz-fit-content;
      max-width: fit-content;
      margin: 0 auto;
      overflow-x: auto;
      white-space: nowrap;
    }
    Especially on mobile, a table can easily become wider than the viewport. Using the right CSS, you can get scrollbars on the table without wrapping it.
    A centered table.

    Explanation: display: block; makes it possible to have scrollbars. By default (and unlike tables), blocks span the full width of the parent element. This can be prevented with max-width: fit-content;, which allows you to still horizontally center tables with less content using margin: 0 auto;. white-space: nowrap; is optional (but useful for this demonstration).

提交回复
热议问题