假设您获得以下 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
您考虑过使用 z-index 吗?
.one {
grid-area: one;
z-index: 1; // Add this
}
.four {
grid-area: four;
z-index: 50; // And add this
}
这样蓝色网格就会隐藏在橙色元素下面。这不是一个非常漂亮的解决方案,但在不更改 html 的情况下无法真正思考任何事情......