首页 > 解决方案 > css - 使 2 显示:table-row 粘在彼此之上

问题描述

我有这个 HTML

.table {
  display: table;
}

.row {
  display: table-row;
}

.cell {
  display: table-cell;
  text-align: center;
  padding: 5px;
  border-right: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
}

.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0px;
  background: red;
}
<body>
  <div class="table">
    <div class="row">
      <div class="cell sticky"><span>Header Row 1</span>
      </div>
    </div>
    <div class="row">
      <div class="cell sticky"><span>Header Row 2</span>
      </div>
    </div>
    <div class="row">
      <div class="cell">Detail Row 1</div>
    </div>
    <div class="row">
      <div class="cell">Detail Row 2</div>
    </div>
    <div class="row">
      <div class="cell">Detail Row 3</div>
    </div>
  </div>
</body>

它使第二个标题行变得粘稠- 正如预期的那样 - 但是如果我希望两个标题行都粘在彼此之上怎么办?- 这样当用户滚动页面时这两行总是可见的?

标签: htmlcsssticky

解决方案


正如我在评论中提到的,您需要top为第二个粘性块设置 。这top应该等于height第一个粘性的。您可以使用伪类定义粘性块的每个父级:nth-child()

30px是第一个粘性块的大致高度。

看一下css代码,你就会明白我的意思了。

.table {
  display: table;
}

.row {
  display: table-row;
}

.cell {
  display: table-cell;
  text-align: center;
  padding: 5px;
  border-right: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
}

.sticky {
  position: -webkit-sticky;
  position: sticky;
  background: red;
}

.row:nth-child(1) .sticky {
  top: 0px;
} 

.row:nth-child(2) .sticky {
  top: 30px;
}

推荐阅读