CSS样式实现表头和列固定
效果图:第一行和第一列固定
DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>CSS实现表头与列固定title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<style>
.main{
width:1000px;
overflow:auto;
height:625px;
}
td,th{
border:1px solid gray;
width:100px;
height:30px;
}
th{
background-color:lightblue;
}
table{
table-layout:fixed;
width:2000px;
}
td:first-child,th:first-child{
position:sticky;
left:0;
z-index:1;
background-color:lightpink;
}
thead tr th{
position:sticky;
top:0;
}
th:first-child{
z-index:2;
background-color:lightblue;
}
style>
head>
<body>
<div id="app">
<div class="main">
<table cellspacing="0">
<thead>
<tr>
<th>{{message}}th>
<th>标题2th>
<th>标题3th>
<th>标题4th>
<th>标题5th>
<th>标题6th>
<th>标题7th>
<th>标题8th>
<th>标题9th>
<th>标题10th>
<th>标题11th>
<th>标题12th>
<th>标题13th>
<th>标题14th>
<th>标题15th>
tr>
thead>
<tbody>
<tr v-for="(item,index) in 50" :key="index">
<td>demo1td>
<td>demo2td>
<td>demo3td>
<td>demo4td>
<td>demo5td>
<td>demo6td>
<td>demo7td>
<td>demo8td>
<td>demo9td>
<td>demo10td>
<td>demo11td>
<td>demo12td>
<td>demo13td>
<td>demo14td>
<td>demo15td>
tr>
tbody>
table>
div>
div>
body>
<script>
var app=new Vue({
el:‘#app‘,
data:{
message:‘hello‘
},
methods:{
clickButton:function(){
this.my_data = "Wow! I‘m changed!"
}
}
})
script>
html>
CSS样式介绍:
1、overflow 属性规定当内容溢出元素框时发生的事情。 值 描述 visible 默认值。内容不会被修剪,会呈现在元素框之外。 hidden 内容会被修剪,并且其余内容是不可见的。 scroll 内容会被修剪,但是浏览器会显示滚动条以便查看其余的内容。 auto 如果内容被修剪,则浏览器会显示滚动条以便查看其余的内容。 inherit 规定应该从父元素继承 overflow 属性的值。 案例: .main{ width:1000px; overflow:auto; height:625px; } 2、table-layout:fixed; 值 描述 automatic 默认。列宽度由单元格内容设定。 fixed 列宽由表格宽度和列宽度设定。 inherit 规定应该从父元素继承 table-layout 属性的值。 案例: table{ table-layout:fixed; width:2000px; } 3、position 属性指定了元素的定位类型 static:HTML 元素的默认值,即没有定位,遵循正常的文档流对象。静态定位的元素不会受到 top, bottom, left, right影响。 fixed:元素的位置相对于浏览器窗口是固定位置。即使窗口是滚动的它也不会移动:Fixed定位使元素的位置与文档流无关,因此不占据空间。 Fixed定位的元素和其他元素重叠。 relative:相对定位元素的定位是相对其正常位置。 absolute:绝对定位的元素的位置相对于最近的已定位父元素, 如果元素没有已定位的父元素,那么它的位置相对于: sticky:sticky 英文字面意思是粘,粘贴,所以可以把它称之为粘性定位。 指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。 z-index属性:指定了一个元素的堆叠顺序。一个元素可以有正数或负数的堆叠顺序 案例: td:first-child,th:first-child{ position:sticky; left:0; z-index:1; background-color:lightpink; }
原文:https://www.cnblogs.com/1314520xh/p/14827684.html