一個表格固定表頭內容滾動

查了挺多方法,都是寫了兩個表格來實現,表頭一個table 內容一個table。但是頁面都寫好了不想改,就直接自己用css進行了控制。弊端:不方便適用於多個頁面。因爲th td的寬度需要固定住。不固定就直接把屏幕寬度等分了。所以,一些內容較多的列需要手動控制寬度。直接上代碼,因公司項目,所以。。

<div>
	<div class="table-head">
		<table id="contentTable">
			<thead>
				<tr>
					<th><input type="checkbox"/></th>
					<th>xxxxx</th>
					<th>xxxxx</th>
					<th>證件號碼</th>
					<th>姓名</th>
					<th>性別</th>
					<th>xxxxx</th>
					<th>出生日期</th>
					<th>xxx</th>
					<th>xxx</th>
					<th>ssss</th>
					<th>xxxx</th>
					<th>ccccc手機</th>
					<th>家庭住址</th>
					<th>xxxxx</th>
					<th>xxxxx</th>
					<th>xxxxx</th>
					<th>修改日期</th>
				</tr>
			</thead>
			<tbody>
				<tr>
                        //18個td  省略
                    </tr>				
			</tbody>
		</table>
	</div>
</div>
/** 這是css */
body{overflow-y: hidden}
#contentTable tbody { display: block; height: 520px; overflow-y: scroll; }
#contentTable thead,
#contentTable tbody tr { display: table; width: 100%; table-layout: fixed; /**表格列的寬度由表格寬度決定,不由內容決定*/ text-align: center; }

/**每一個th都要和對應的td寬度相同,如果不設置,則默認均分寬度,我設置的都是一些內容較多的,比如說身份證號碼,電話,住址等*/
#contentTable tr th:nth-of-type(1),#contentTable tr td:nth-of-type(1){width: 1.5%;}
#contentTable tr th:nth-of-type(2),#contentTable tr td:nth-of-type(2){width: 8.5%;}
#contentTable tr th:nth-of-type(3),#contentTable tr td:nth-of-type(3){width: 7%;}
#contentTable tr th:nth-of-type(4),#contentTable tr td:nth-of-type(4){width: 8.5%;}
#contentTable tr th:nth-of-type(8),#contentTable tr td:nth-of-type(8){width: 5%;}
#contentTable tr th:nth-of-type(9),#contentTable tr td:nth-of-type(9){width: 5%;}
#contentTable tr th:nth-of-type(12),#contentTable tr td:nth-of-type(12){width: 8.5%;}
#contentTable tr th:nth-of-type(13),#contentTable tr td:nth-of-type(13){width: 6%;}
#contentTable tr th:nth-of-type(14),#contentTable tr td:nth-of-type(14){width: 15%;}
#contentTable tr th:nth-of-type(16),#contentTable tr td:nth-of-type(16){width: 5%;}
#contentTable tr th:nth-of-type(18),#contentTable tr td:nth-of-type(18){width: 5%;}

/**這一個重要:寫完上面的看效果應該是表頭和內容對不齊。我們需要的是調節0.4em中的0.4,試着變大變小就能看到區別,我試了,剛好跳到0.4,所有的列都能垂直對齊*/
#contentTable thead { width: calc( 100% - 0.4em);/*表頭與表格垂直對齊*/ }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章