表格制作
1、table的常用属性
1.1、cellspacing和cellspadding区别
属性 含义 常用属性值
cellspacing 设置单元格与单元格边框之间的空白间距 像素值(默认为2px)
cellspadding 设置单元格内容与单元格边框之间的空白距离 像素值(默认为1px)
1.2、table-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;
background-color: bisque;
z-index: 10;
}
4、常见问题
4.1、当外层div固定宽高后,对table每个单元格th和tb的width设置后,当行的单元格width的总和超过div的width时,此时单元格的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>
.box {
overflow: auto;
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;
background-color: bisque;
z-index: 10;
}
</style>