如何将粘性元素仅保留在两个 CSS 网格行上?

问题描述 投票:0回答:1

假设您获得以下 HTML:

<div class="grid">
  <div class="sticky blue one" style="height: 50px !important"></div>
  <div class="red two"></div>
  <div class="green three"></div>
  <div class="orange four" style="height: 1500px !important;"></div>
</div>

,其中网格提供两列;第一个元素生成两行,最后一个元素生成两列,如下所示:

如何在不更改 HTML 的情况下使蓝色元素具有粘性 (

position: sticky
),但只能粘到橙色元素?

网上有一些资源建议使用

align-self
,但我还没有找到可行的解决方案。

这是当前状态,蓝色元素滚动到橙色元素上:

.grid {
  display: grid;
  width: 100%;
  gap: 1rem;
  background-color: aliceblue;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: auto auto;
  grid-template-areas: "one two" "one three" "four four";
}

.grid>div {
  height: 500px;
  width: 100%;
}

.sticky {
  position: sticky;
  top: 5px;
}


/**
* Placement
*/

.one {
  grid-area: one;
}

.two {
  grid-area: two;
}

.three {
  grid-area: three;
}

.four {
  grid-area: four;
}


/**
* Colours
*/

.blue {
  background-color: blue;
}

.red {
  background-color: red;
}

.orange {
  background-color: orange;
}

.green {
  background-color: green;
}
<div class="grid">
  <div class="sticky blue one" style="height: 50px !important"></div>
  <div class="red two"></div>
  <div class="green three"></div>
  <div class="orange four" style="height: 1500px !important;"></div>
</div>

这里有一个 codepen 的链接:https://codepen.io/BernhardWebstudio/pen/mdQZMwW

html css css-position css-grid sticky
1个回答
0
投票

您考虑过使用 z-index 吗?

.one {
  grid-area: one;
  z-index: 1; // Add this
}
.four {
  grid-area: four;
  z-index: 50; // And add this
}

这样蓝色网格就会隐藏在橙色元素下面。这不是一个非常漂亮的解决方案,但在不更改 html 的情况下无法真正思考任何事情......

© www.soinside.com 2019 - 2024. All rights reserved.