table实现行列固定

514 阅读1分钟

表格制作

1table的常用属性
   1.1、cellspacing和cellspadding区别
		属性	含义	常用属性值
		cellspacing	设置单元格与单元格边框之间的空白间距	像素值(默认为2px)
		cellspadding	设置单元格内容与单元格边框之间的空白距离	像素值(默认为1px)
   1.2table-layout
        fixed: 列宽由表格宽度和列宽度设定。
        auto: 默认。列宽度由单元格内容设定。
		inherit:  规定应该从父元素继承 table-layout 属性的值。
2、固定行
   /* 固定行 */
   thead th {
   	background-color: antiquewhite;
   	position: sticky;
   	position: -webkit-sticky;
   	top: 0;
   }
   
   thead th:first-child {
   	z-index: 20;
   }
3、固定列
   /**固定首列**/
   th:first-child , td:first-child {
   	position: sticky; /* 首列使用粘性属性,固定到原位置 */
   	position: -webkit-sticky;
   	left: 0; /* 使用sticky时需要配置定位标识 */
   	background-color: bisque;
   	z-index: 10; /* 在滑动时,后面的内容会覆盖掉前首列单元,需要设置z级别 */
   }

4、常见问题
   4.1、当外层div固定宽高后,对table每个单元格th和tb的width设置后,当行的单元格width的总和超过divwidth时,此时单元格的width
        无效,会出现自动平分每个单元格,具体原因是 table-layout默认auto,它是列宽根据内容自适应。
		解决方式:table上的table-layout属性修改成fixed,固定表格,对应的列宽将影响到整体表格宽高
		demo
		<div>
		  <table>
		     <thead>
				<tr><th></th><th></th><th></th><th></th></tr>
			 </thead>
			 <tbody>
			    <tr><td></td><td></td><td></td><td></td></tr>
				<tr><td></td><td></td><td></td><td></td></tr>
				<tr><td></td><td></td><td></td><td></td></tr>
			 </tbody>
		  </table>
		</div>
		<style>
			/**
			 * 最外层盒子处理
			 * 1、设置边框 考虑每列的边框是 右边、下边框,最外层盒子就进设置左边、上边框
			 * 2、固定宽高,当出现内容溢出时,自动显示滚动条
			 * 3、table标签中消除每个列格原生的占用空间,
			 *    cellspacing="0"  // 消除每个单元格的间距
			 *    cellpadding="0"  // 消除每个单元格的内间距
			**/
			.box {
				overflow: auto; /*table列超出宽度后,自动出现滚动条*/
				width: 300px;
				//height: 240px;
				border: 1px solid #DCDCDC;
				border-right: 0;
				border-bottom: 0;
				box-sizing: border-box;
			}
			
			table {
				border-collapse: separate; /**处理边框重叠情况**/
				table-layout: fixed; /**固定表格,使单元格宽度可设置**/
				width: 100%;
			}
			
		    th,td {
				width: 100px;
				height: 20px;
				border-right: 1px solid #DCDCDC;
				border-bottom: 1px solid #DCDCDC;
			}
			
			/* 固定行 */
			thead th {
				background-color: antiquewhite;
				position: sticky;
				position: -webkit-sticky;
				top: 0;
			}
			
			thead th:first-child {
				z-index: 20;
			}
			
			/**固定首列**/
			th:first-child , td:first-child {
				position: sticky; /* 首列使用粘性属性,固定到原位置 */
				position: -webkit-sticky;
				left: 0; /* 使用sticky时需要配置定位标识 */
				background-color: bisque;
				z-index: 10; /* 在滑动时,后面的内容会覆盖掉前首列单元,需要设置z级别 */
			}
		</style>