table下tbody滾動條與thead對齊的方法且每一列可以不均等


1 前言

table下tbody滾動條與thead對齊的方法,開始在tbody的td和thead的tr>td,對每一個Item加入百分比,結果是沒對齊。也嘗試了用bootstrap的col-md-1等來對齊,也是對不齊。然后只能網上查找答案了,就只需看用CSS來控制樣式即可達到目的

2 代碼

核心代碼:

<style>
table tbody {
    display:block; //core code
    height:200px;
    overflow-y:scroll;
}

table thead, tbody tr {
    display:table;
    width:100%;
    table-layout:fixed;//core code
}

table thead {
    width: calc( 100% - 1em )//core code
}
</style>

如果只要上面的配置,默認是均等平分table大小的。

完整樣例代碼如下:

<!DOCTYPE html>
<html>
<head>
	<title>Test table tbody is alignment with thead</title>
	<style type="text/css">
		.per20{
			width:20%;
		}
		.per10{
			width:10%;
		}	
		.per40{
			width:40%;
		}
		 		
		table tbody {
			 display: block; 
			 height:150px; 
			 overflow:auto;
		}
		
		table thead, tbody tr {
		    display:table;
		    width:100%;
		    table-layout:fixed;
		    text-align: left;//If disabled, default align central
		}
		
		table thead {
		    width: calc( 100% - 1em )
		}
	</style>
	<script>
		window.onload=function(){
			var contentSum = "";
			for(i = 0; i < 16; i++){
				var content = '<tr>'
							+ '<td class="per10">'+i+'</td>'
							+ '<td class="per10">BBB</td>'
							+ '<td class="per20">CCCcontent</td>'
							+ '<td class="per10">DDD</td>'
							+ '<td class="per40">EEEBigbig</td>'
							+ '<td class="per10">FFFXXX</td>'
							+'</tr>';
				contentSum += content;
			}
			//$('#content').html(contentSum);
			document.getElementById('content').innerHTML=contentSum;
	}
	</script>
	
</head>
<body>

	<table border="1px solid" width="900px">
		<thead>
			<tr>
				<th class="per10">A</th>
				<th class="per10">BBB</th>
				<th class="per20">CCCCCCCCCC</th>
				<th class="per10">D</th>
				<th class="per40">EEEEEEEEEEEEEE</th>
				<th class="per10">FFF</th>
			</tr>
		</thead>
		<tbody id="content">
		<!--  	<tr>
				<td class="per10">1</td>
				<td class="per10">BBB</td>
				<td class="per20">CCCcontent</td>
				<td class="per10">DDD</td>
				<td class="per40">EEEBigbig</td>
				<td class="per10">FFFXXX</td>
			</tr> -->			
		</tbody>
	</table>

	</body>
</html>
 	

3 效果圖

4 參考

http://www.weste.net/2016/01-15/108242.html

   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM