Using position: sticky
has been a game-changer for me. It resolves many issues without the need for JavaScript. However, I've encountered a roadblock. I am trying to create a sticky element that is nested inside multiple <div>
elements. Since position: sticky
functions as a blend of position: relative
and position: fixed
, it naturally anchors to its first parent.
As per MDN's explanation:
The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor)
In my case, I'm looking to make a header sticky in relation to the window rather than its container. Unfortunately, the structure of the HTML complicates moving it outside the nested <div>
.
Is there a way to achieve this without using JavaScript?
Below is the code snippet:
<div class="attendance">
<!-- The header I want to stick to the window, and not to div.attendance-->
<header class="text-center sticky">Monday 11/22/2019</header>
<!-- Header above -->
<div class="date-config">
<div class="form-group">
<input type="checkbox" id="workable" /> No Work<br />
</div>
<div class="form-group">
<label for="notes">Notes:</label>
<textarea id="notes" class="form-control"></textarea>
</div>
<label for="markall">Mark all as>
<select id="markall" class="form-control">
<option></option>
<option>Absent</option>
<option>Present</option>
</select>
</div>
<div class="student-attendance">
Hello :)
</div>
</div>
Does anyone have suggestions on how to tackle this issue?
P.S: While researching, I came across this resource, but it relies on JavaScript.
Edit: Here's an unconventional yet functional demo (Note: It's in Spanish - Focus on the dates! They do not stay anchored to the window!).