CSS3实现响应式数据表格

原创文章 作者:月光光 2015年06月19日 11:42helloweba.com 标签:CSS3 

设计响应式页面的时候,最难的是表格table的处理,table作为数据表格设计不可缺少的元素,在数据应用项目中起着重要的作用,但是要想让表格适应各种屏幕还真有点麻烦。本文将用实例给大家演示如何使用CSS3来实现的响应式数据表格。

当屏幕足够小(如手机屏幕),以至于小于表格的最小宽度,如果不做响应式处理,那么将会出现水平滚动条,需要手动移动放大来查看超出屏幕的部分,这样体验很差。我们的解决办法是使用CSS @media queries来检测屏幕尺寸,当屏幕尺寸足够小的时候,重新布局table表格。

HTML

假设我们有一个如下的数据表格,当然它可能有更多的列,文中代码只用了3列。

<table>
	<thead>
		<tr>
			<th>姓名</th>
			<th>性别</th>
			<th>出生年月</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>蒋介</td>
			<td>男</td>
			<td>1998.2.5</td>
		</tr>
		<tr>
			<td>许维</td>
			<td>女</td>
			<td>1998.2.1</td>
		</tr>
	</tbody>
</table>

CSS3

首先,我们使用一些简单的css代码就可以呈现一个基本的table表格,css代码并没有特别的地方。

table { 
  width: 100%; 
  border-collapse: collapse; 
}
tr:nth-of-type(odd) { 
  background: #eee; 
}
th { 
  background: #333; 
  color: white; 
  font-weight: bold; 
}
td, th { 
  padding: 6px; 
  border: 1px solid #ccc; 
  text-align: left; 
}

这个时候,我们使用电脑浏览器打开页面,发现展示了一个简单的表格,随着浏览器窗口的缩小,表格宽度会变小,但当浏览器窗口足够小的时候,问题就来了,表格宽度由于表格单元的内容撑着无法再变小,从而出项横向滚动条的情况,那么下面的css3代码提供了解决方案。

我们要做的是,使用css3的@media检测到屏幕尺寸,将表格元素设置为block块状,并且隐藏表头,将td设置下边框看起来跟一行行的一样。最后我们使用css3的:before { content: "姓名"; }生成每行对应的标签定义,这样就能知道每行数据的意义。

@media 
only screen and (max-width: 760px),
(min-device-width: 768px) and (max-device-width: 1024px)  {

	/* Force table to not be like tables anymore */
	table, thead, tbody, th, td, tr { 
		display: block; 
	}
	thead tr { 
		position: absolute;
		top: -9999px;
		left: -9999px;
	}
	
	tr { border: 1px solid #ccc; }
	
	td { 
		/* Behave  like a "row" */
		border: none;
		border-bottom: 1px solid #eee; 
		position: relative;
		padding-left: 50%; 
	}
	
	td:before { 
		/* Now like a table header */
		position: absolute;
		/* Top/left values mimic padding */
		top: 6px;
		left: 6px;
		width: 45%; 
		padding-right: 10px; 
		white-space: nowrap;
	}
	
	/*
	Label the data
	*/
	td:nth-of-type(1):before { content: "姓名"; }
	td:nth-of-type(2):before { content: "性别"; }
	td:nth-of-type(3):before { content: "出生年月"; }
}

现在你用手机打开页面,你会发现表格的布局变了,它是这样的:

当然,本例也不是最佳解决方案,有兴趣的朋友可以参照bootstrap关于响应式表格的处理。

声明:本文为原创文章,helloweba.net和作者拥有版权,如需转载,请注明来源于helloweba.net并保留原文链接:https://www.helloweba.net/javascript/309.html

2条评论

  • 很棒的办法

  • 请问,为啥我这个弄出来, td:nth-of-type(1):before { content: "姓名"; }
    td:nth-of-type(2):before { content: "性别"; }
    td:nth-of-type(3):before { content: "出生年月"; } 这些内容和值重合了呢?