CSS表响应格式

时间:2014-09-11 01:23:36

标签: html css responsive-design html-table

我还没有找到确切的示例,所以如果你有,请指点我。

我想让HTML中的表格响应如下 - 是否可以使用CSS?

<table>
   <thead>
      <tr>
         <td>HEADER Data 1</td>
         <td>HEADER Data 2</td>
         <td>HEADER Data 3</td>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>Row 1 Data 1</td>
         <td>Row 1 Data 2</td>
         <td>Row 1 Data 3</td>
      </tr>
      <tr>
         <td>Row 2 Data 1</td>
         <td>Row 2 Data 2</td>
         <td>Row 2 Data 3</td>
      </tr>
      <tr>
         <td>Row 3 Data 1</td>
         <td>Row 3 Data 2</td>
         <td>Row 3 Data 3</td>
      </tr>
   </tbody>
</table>

在小屏幕上,我希望表格具有响应性,以便将数据放置如下:

HEADER Data 1
Row 1 Data 1
Row 1 Data 2
Row 1 Data 3

HEADER Data 2
Row 2 Data 1
Row 2 Data 2
Row 2 Data 3

HEADER Data 3
Row 3 Data 1
Row 3 Data 2
Row 3 Data 3

2 个答案:

答案 0 :(得分:3)

我希望这有助于使表格响应。

  

这里是fiddle

HTML:

<table>
    <thead>
        <tr>
            <td>Name</td>
            <td>Age</td>
            <td>Gender</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Qasim</td>
            <td>23yrs</td>
            <td>Male</td>
        </tr>
        <tr>
            <td>Ali</td>
            <td>19yrs</td>
            <td>Male</td>
        </tr>
        <tr>
            <td>William</td>
            <td>34yrs</td>
            <td>Male</td>
        </tr>
    </tbody>
</table>

CSS:

td{
  width:100px;
}
@media (max-width: 600px) {
    thead {
        display: none;
    }
    tr{
      display:grid;
      border-bottom:1px solid #000000;
    }
    td:nth-of-type(1):before { content: "Name"; }
    td:nth-of-type(2):before { content: "Age"; }
    td:nth-of-type(3):before { content: "Gender"; }

    td:before{
      width:150px;
      float:left;
    }
    td{
      width:300px;
    }

}

答案 1 :(得分:1)

将每个标头的副本放在相应的行中,并使用CSS伪选择器:first-child隐藏它。然后使用媒体查询来更改布局,隐藏正常的标题,并显示隐藏的标题。

HTML:

<table>
    <thead>
        <tr>
            <td>HEADER Data 1</td>
            <td>HEADER Data 2</td>
            <td>HEADER Data 3</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>HEADER Data 1</td>
            <td>Row 1 Data 1</td>
            <td>Row 1 Data 2</td>
            <td>Row 1 Data 3</td>
        </tr>
        <tr>
            <td>HEADER Data 2</td>
            <td>Row 2 Data 1</td>
            <td>Row 2 Data 2</td>
            <td>Row 2 Data 3</td>
        </tr>
        <tr>
            <td>HEADER Data 3</td>
            <td>Row 3 Data 1</td>
            <td>Row 3 Data 2</td>
            <td>Row 3 Data 3</td>
        </tr>
    </tbody>
</table>

CSS:

tbody tr td:first-child {
    display: none;
}
@media (max-width: 600px) {
    thead {
        display: none;
    }
    td {
        display: block;
        clear: left;
    }
    tbody tr td:first-child {
        display: block;
    }
}

这里是fiddle