|
|
|
|
|
當表格內容太多的時候,固定表頭不讓標題滾出屏幕外,是一個很人性化的設計;而當橫向項目內容太多時,固定第一列(項目列)也是一個很貼心的設計。本文介紹如何用CSS實現(xiàn)固定Table表頭和第一列。
固定Table表頭和第一列
CSS
table {
font-family: "Fraunces", serif;
font-size: 125%;
white-space: nowrap;
margin: 0;
border: none;
border-collapse: separate;
border-spacing: 0;
table-layout: fixed;
border: 1px solid black;
}
table td,
table th {
border: 1px solid black;
padding: 0.5rem 1rem;
}
table thead th {
padding: 3px;
position: sticky;
top: 0;
z-index: 1;
width: 25vw;
background: white;
}
table td {
background: #fff;
padding: 4px 5px;
text-align: center;
}
table tbody th {
font-weight: 100;
font-style: italic;
text-align: left;
position: relative;
}
table thead th:first-child {
position: sticky;
left: 0;
z-index: 2;
}
table tbody th {
position: sticky;
left: 0;
background: white;
z-index: 1;
}
caption {
text-align: left;
padding: 0.25rem;
position: sticky;
left: 0;
}
[role="region"][aria-labelledby][tabindex] {
width: 450px;
height: 400px;
overflow: auto;
box-shadow: 0 0 0.8em rgba(0, 0, 0, 0.5);
outline: 0;
}
HTML
<div role="region" aria-labelledby="caption" tabindex="0">
<table>
<caption id="caption">棒球號碼</caption>
<thead>
<tr>
<th>Teams</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
<th>9</th>
<th>Runs</th>
</tr>
</thead>
<tbody>
<tr>
<th>Milwaukee Brewers</th>
<td>2</td>
<td>0</td>
<td>4</td>
<td>1</td>
<td>0</td>
<td>3</td>
<td>0</td>
<td>3</td>
<td>4</td>
<td>17</td>
</tr>
<tr>
<th>Los Angles Dodgers</th>
<td>0</td>
<td>2</td>
<td>3</td>
<td>1</td>
<td>3</td>
<td>4</td>
<td>3</td>
<td>2</td>
<td>4</td>
<td>22</td>
</tr>
</tbody>
</table>
</div>
代碼解釋
這里的“技巧”部分是position: sticky;
用法,但更重要的是你必須知道如何處理重疊元素。
固定表格單元格需要有背景,否則我們會看到重疊的內容。它還需要適當?shù)?code>z-index處理,以便當它固定到位時,它會位于它應該位于的頂部。這感覺是最棘手的部分:
tbody>th
單元格位于常規(guī)表格單元格上方,以便它們在水平滾動期間保持在頂部。thead>th
單元格在這些單元格之上,以便垂直滾動。thead>th:first-child
單元格是最高的,因為它需要位于正文單元格上方,并且它又是水平滾動的同級標題。只固定Table表頭
如果只想固定Table表頭,那么很簡單,我們只需把前面的HTML代碼<th>...</th>
這列即是第一列去掉即可。
只固定Table表頭