仅使用 css/bootstrap 粘性多个表头 (thead) 行

phi*_*her 5 html css bootstrap-4

我试图在<thead>标签下粘贴多行,而表格的其余部分是可滚动的。

SO 上的这个答案显示了如何使用标签将标题粘贴到顶部position: sticky,但没有显示如何在<thead>.

使用链接中提到的 CSS 代码thead th { position: sticky; top: 0; }只会粘贴 中的第一行<thead>

谢谢您的帮助!

Sam*_*eer 9

如果两个顶部值相同,则它将相互重叠,top用第一个标头的值更改第二个标头的值height。如下所示

\n\n
thead tr:nth-child(1) th { position: sticky; top: 0; }\nthead tr:nth-child(2) th { position: sticky; top: 43px; }\n
Run Code Online (Sandbox Code Playgroud)\n\n

top: 43px是第一个标题的高度

\n\n

完整示例
\n//HTML

\n\n
<table id="customers">\n<thead>\n  <tr>\n    <th>Company</th>\n    <th>Contact</th>\n    <th>Country</th>\n  </tr>\n  <tr>\n    <th>Company 2</th>\n    <th>Contact 2</th>\n    <th>Country 2</th>\n  </tr>\n  </thead>\n  <tr>\n    <td>Alfreds Futterkiste</td>\n    <td>Maria Anders</td>\n    <td>Germany</td>\n  </tr>\n  <tr>\n    <td>Berglunds snabbk\xc3\xb6p</td>\n    <td>Christina Berglund</td>\n    <td>Sweden</td>\n  </tr>\n  <tr>\n    <td>Centro comercial Moctezuma</td>\n    <td>Francisco Chang</td>\n    <td>Mexico</td>\n  </tr>\n  <tr>\n    <td>Ernst Handel</td>\n    <td>Roland Mendel</td>\n    <td>Austria</td>\n  </tr>\n  <tr>\n    <td>Island Trading</td>\n    <td>Helen Bennett</td>\n    <td>UK</td>\n  </tr>\n  <tr>\n    <td>K\xc3\xb6niglich Essen</td>\n    <td>Philip Cramer</td>\n    <td>Germany</td>\n  </tr>\n  <tr>\n    <td>Laughing Bacchus Winecellars</td>\n    <td>Yoshi Tannamuri</td>\n    <td>Canada</td>\n  </tr>\n  <tr>\n    <td>Magazzini Alimentari Riuniti</td>\n    <td>Giovanni Rovelli</td>\n    <td>Italy</td>\n  </tr>\n  <tr>\n    <td>North/South</td>\n    <td>Simon Crowther</td>\n    <td>UK</td>\n  </tr>\n  <tr>\n    <td>Paris sp\xc3\xa9cialit\xc3\xa9s</td>\n    <td>Marie Bertrand</td>\n    <td>France</td>\n  </tr>\n  <tr>\n    <td>Some repeated content</td>\n    <td>Some repeated content</td>\n    <td>Some repeated content</td>\n  </tr>\n  <tr>\n    <td>Some repeated content</td>\n    <td>Some repeated content</td>\n    <td>Some repeated content</td>\n  </tr>\n  <tr>\n    <td>Some repeated content</td>\n    <td>Some repeated content</td>\n    <td>Some repeated content</td>\n  </tr>\n  <tr>\n    <td>Some repeated content</td>\n    <td>Some repeated content</td>\n    <td>Some repeated content</td>\n  </tr>\n\n</table>\n
Run Code Online (Sandbox Code Playgroud)\n\n

//CSS

\n\n
#customers {\n  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;\n  border-collapse: collapse;\n  width: 100%;\n}\n\n#customers td, #customers th {\n  border: 1px solid #ddd;\n  padding: 8px;\n}\n\n#customers tr:nth-child(even){background-color: #f2f2f2;}\n\n#customers tr:hover {background-color: #ddd;}\n\n#customers th {\n  padding-top: 12px;\n  padding-bottom: 12px;\n  text-align: left;\n  background-color: #4CAF50;\n  color: white;\n}\nthead tr:nth-child(1) th { position: sticky; top: 0; }\nthead tr:nth-child(2) th { position: sticky; top: 43px; }\n
Run Code Online (Sandbox Code Playgroud)\n\n

jsfiddle的示例链接

\n