Issue
I am trying to add a sticky element that stays on the bottom of the page only when it enters the viewport. The idea is that the element would be placed somewhere in the middle of the page and would not be shown immediately when the user visits the page.
Here's my progress so far:
div {
height: 300px;
}
.sticky {
position: -webkit-sticky;
position: sticky;
bottom: 0;
height: 30px;
width: 100vw;
background: yellow;
}
<div style="background: red;">Scroll</div>
<div style="height: 300px; background: orange;"></div>
<div class="sticky">Sticky Section</div>
<div style="background: green;"></div>
<div style="background: blue;"></div>
The problem is that my code does the opposite of what I want it to do. The element should only stick past its original location.
Changing bottom: 0 to top: calc(100vh - 30px) on .sticky seems to work fine on desktop, but I noticed it's not adequate for Safari on iOS. With this 'hacked' solution, whenever the user scrolls up, the bottom bar increases in size and forces the sticky element to jump.
Solution
Sticky position can be a little confusing and frustrating at times.
The key to solving this problem is to keep in mind that a sticky element will appear at the top of its parent element. So by splitting or encapsulating the page's content into 2 sections we can create your desired outcome.
The first section contains content and no sticky element,
The second section contains content and the desired sticky element which will appear at the top of this element
We can decide where on the page the sticky element first appears by where we create the split between the 2 sections or more appropriately where the 2 section starts.
Below is example code where the sticky element appears in the middle of the page.
//
.sticky {
position: -webkit-sticky;
position: sticky;
bottom: 0;
height: 30px;
width: 100vw;
background: yellow;
}
<!-- Content you want before the sticky element -->
<div>
<div style="height: 300px; background: red;">Scroll</div>
<div style="height: 300px; background: orange;"></div>
</div>
<!-- Content you want after the sticky element -->
<div>
<!-- The sticky element will appear as if its been placed here -->
<div style="height: 300px; background: green;"></div>
<div style="height: 300px; background: blue;"></div>
<div class="sticky">Sticky Section</div>
</div>
Answered By - Mernlin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.