html表格如何做成响应式,响应式表格仅用HTML和CSS
时间: 2024-03-09 20:46:10 浏览: 24
要使HTML表格响应式,您可以使用CSS中的媒体查询来根据屏幕大小和设备类型更改表格的样式和布局。以下是一个简单的例子:
HTML代码:
```
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>国籍</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>25</td>
<td>中国</td>
</tr>
<tr>
<td>John Doe</td>
<td>30</td>
<td>美国</td>
</tr>
</tbody>
</table>
```
CSS代码:
```
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
/* 媒体查询 */
@media screen and (max-width: 600px) {
/* 将表格行转换为块级元素,以便在小屏幕上垂直排列 */
table, thead, tbody, th, td, tr {
display: block;
}
/* 隐藏表头 */
thead tr {
position: absolute;
top: -9999px;
left: -9999px;
}
/* 将单元格堆叠在一起 */
td {
position: relative;
padding-left: 50%;
}
td:before {
position: absolute;
left: 6px;
content: attr(data-label); /* 使用自定义属性来显示列标题 */
}
}
```
此CSS代码使用媒体查询来检测屏幕宽度是否小于600px,如果是,则将表格转换为块级元素,并对其进行垂直排列。它还隐藏了表头,将单元格堆叠在一起,并使用:before伪元素显示列标题。使用自定义属性data-label可以在移动设备上更好地显示列标题。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)