Ich war ein bisschen festgefahren und dachte, ich würde dies teilen position: sticky
+ flex box gotcha:
Mein klebriges Div funktionierte einwandfrei, bis ich meine Ansicht auf einen Flexbox-Container umstellte, und plötzlich war das Div nicht mehr klebrig, als es in ein übergeordnetes Flexbox-Element eingewickelt war.
.flexbox-wrapper {
display: flex;
height: 600px;
}
.regular {
background-color: blue;
}
.sticky {
position: -webkit-sticky;
position: sticky;
top: 0;
background-color: red;
}
<div class="flexbox-wrapper">
<div class="regular">
This is the regular box
</div>
<div class="sticky">
This is the sticky box
</div>
</div>
Da Flexbox-Elemente standardmäßig stretch
sind, haben alle Elemente die gleiche Höhe, gegen die nicht gescrollt werden kann.
Durch Hinzufügen von align-self: flex-start
Zum Sticky-Element wird die Höhe auf auto gesetzt, wodurch das Scrollen möglich ist, und es wird korrigiert.
Derzeit ist dies nur nterstützt in Safari und Edge
.flexbox-wrapper {
display: flex;
overflow: auto;
height: 200px; /* Not necessary -- for example only */
}
.regular {
background-color: blue; /* Not necessary -- for example only */
height: 600px; /* Not necessary -- for example only */
}
.sticky {
position: -webkit-sticky;
position: sticky;
top: 0;
align-self: flex-start; /* <-- this is the fix */
background-color: red; /* Not necessary -- for example only */
}
<div class="flexbox-wrapper">
<div class="regular">
This is the regular box
</div>
<div class="sticky">
This is the sticky box
</div>
</div>