This method has proven effective for me, even on iOS devices (after the initial scroll from the top). To see a demonstration, check out this JSFiddle:
https://jsfiddle.net/fcoxg2kL/
Unfortunately, there isn't a perfect solution that meets the exact requirements of the original poster. The issue lies in how Apple handles the position: fixed
property. While my solution works well on iOS after the initial scroll, it also functions correctly on other non-Apple devices like Android. It's essential for developers to consider the broader user base, rather than focusing solely on Apple devices. Despite its limitations on initial scrolling for iOS, my approach represents a step in the right direction.
Regrettably, this problem ultimately rests with Apple for resolution.
The setup I've implemented is fairly straightforward - applying a class when a certain distance (greater than 200px) from the top of the page is reached. The class I've used is madesticky
. In the CSS, this class switches the positioning from position: relative;
to position: fixed;
.
It is my hope that this suggestion will either meet your needs or guide you in the right direction towards a suitable solution.
CSS:
.stickynav {
position: relative;
width: 100%;
background-color: #000;
}
.stickynav.madesticky {
position: fixed;
top: 0;
left: 0;
z-index: 5;
}
.stickynav *::before,
.stickynav *::after,
.stickynav * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.stickynav_inner {
margin: 0 auto;
width: 100%;
max-width: 1000px;
}
.navlist { margin: 0; padding: 0; }
.navlist ul { list-style-type: none; }
.navlist li { display: block; float: left; }
.navlist a {
padding: 10px 15px;
display: block;
color: #fff;
text-decoration: none;
}
.navlist a:hover {
background-color: #454545;
}
HTML:
<div style="height: 200px;"></div>
<div class="stickynav">
<div class="stickynav_inner">
<ul class="navlist">
<li><a href="#">Nav Item 1</a></li>
<li><a href="#">Nav Item 2</a></li>
<li><a href="#">Nav Item 3</a></li>
</ul>
<div style="clear: both;"></div>
</div>
</div>
<div style="height: 2000px;"></div>
JQuery:
/**
* Header Scroll with Add/Remove Class Function
*/
function headerScrollResize(){
var scroll = $(window).scrollTop();
if (scroll < 200) {
$(".stickynav").removeClass("madesticky");
}
if (scroll >= 200) {
$(".stickynav").addClass("madesticky");
}
}
$(window).on('load scroll', function(){
headerScrollResize();
});