I want to stick a certain div to the top when scrolling below it. After some research I found this solution. Everything works fine except that the content of the div shifts a little bit to the left when scrolling over it
javascript
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('#sticky').addClass('stick');
} else {
$('#sticky').removeClass('stick');
}
}
$(function () {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
CSS
#sticky {
padding: 0.5ex;
font-size: 2em;
border-radius: 0.5ex;
}
#sticky.stick {
position: fixed;
top: 0;
z-index: 10000;
border-radius: 0 0 0.5em 0.5em;
}
HTML
<hr />
<div id="sticky-anchor"></div>
<div id="sticky">
<center>Unternehmen Leistungen Kunden Stärken</center>
<hr /></div>
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('#sticky').addClass('stick');
} else {
$('#sticky').removeClass('stick');
}
}
$(function() {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
#sticky {
padding: 0.5ex;
font-size: 2em;
border-radius: 0.5ex;
}
#sticky.stick {
position: fixed;
top: 0;
z-index: 10000;
border-radius: 0 0 0.5em 0.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr />
<div id="sticky-anchor"></div>
<div id="sticky">
<center>Unternehmen Leistungen Kunden Stärken</center>
<hr />
</div>
You have to center the div
to prevent that shift. To center a div
with a position:fixed;
, you need to set left
and right
to 0.
The CSS
#sticky.stick {
position: fixed;
top: 0;
left:0;
right:0;
z-index: 10000;
}
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top) {
$('#sticky').addClass('stick');
} else {
$('#sticky').removeClass('stick');
}
}
$(function() {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
#sticky {
position:relative;
padding: 0.5ex;
font-size: 2em;
text-align:center;
}
#sticky.stick {
position: fixed;
top: 0;
left:0;
right:0;
z-index: 10000;
}
.content {
height:1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr />
<div id="sticky-anchor"></div>
<div id="sticky">
Unternehmen Leistungen Kunden Stärken
<hr />
</div>
<div class="content"></div>