Force html table into single stacked column using only css and no javascript

前端 未结 8 1140
时光取名叫无心
时光取名叫无心 2021-01-02 10:47

I\'m creating a html template that wraps a table that is used to lay out a form. I have full control over the html that wraps the table not the table itself. The table is in

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-02 11:13

    I was confronted with a similar problem recently & seem to have found a good solution. Tables have a bad rap due to frequent mis-use, but are indeed the leanest option when needing to display a grid of data in a variable width viewport.

    The answer to the original question is still no. In order to solve this problem without JavaScript, one must be able to edit the table markup.

    Tables can look... okay... when stretched wide, but look just terrible when squished. "Responsive" tables are possible only by adding contextual markup to each cell (e.g. span.label & span.data elements). We can easily hide this new superfluous output by default & only show it when in a responsive view state.

    table.responsive td .label {
      display: none;
    }
    Column Foo Column Bar
    Column FooBaz Column BarQux

    When in a responsive view state, hide the thead element & show the .label elements.

    table.responsive {
      width: 100%;
    }
    table.responsive td .label {
      display: none;
    }
    
    table.responsive th {
      background-color: #ffffd;
    }
    
    table.second {
      margin-top: 5em;
    }
    
    @media screen and (max-width:640px) {
      table.responsive thead {
        display: none;
      }
      table.responsive tbody th,
      table.responsive tbody td {
        display: block;
      }
    
      table.responsive td span {
        display: block;
      }
      table.responsive td .label {
        background-color: #ffffd;
        font-weight: bold;
        text-align: center;
      }
    }

    I've created a repo which covers the solution in greater detail. Click here to see it work.

提交回复
热议问题