I am trying to create a "sticky" navigation on my page where a div gets position:fixed;
once the user has scrolled to the element. The functionality is working as expected, but the widths of the two columns that are supposed to stick to the top change once the sticky class is added. I tried adding width:100%;
to the CSS of the sticky element, but then the element expands beyond the container.
How can I make sure the column widths stay where they should be when position:fixed;
is added?
HMTL:
<div class="container">
<div class="padding"></div>
<div class="anchor"></div>
<div class="row sticky">
<div class="col-sm-6">
Testing
</div>
<div class="col-sm-6">
Testing
</div>
</div>
<div class="padding2"></div>
</div>
CSS:
.padding {
height:250px;
}
.padding2 {
height:1000px;
}
.sticky {
background:#000;
height:50px;
line-height:50px;
color:#fff;
font-weight:bold;
}
.sticky.stick {
position:fixed;
top:0;
z-index:10000;
}
JS:
function stickyDiv() {
var top = $(window).scrollTop();
var divTop = $('.anchor').offset().top;
if (top > divTop) {
$('.sticky').addClass('stick');
} else {
$('.sticky').removeClass('stick');
}
}
$(window).scroll(function(){
stickyDiv();
});
stickyDiv();
Thanks!
it does not work. with position: fixed the element is out of the normal flow and it doesn't respect it's parent width.
Add . w-auto class to the table element to set an auto width to the table column. The width of the columns will automatically adjust to the content of the column.
Set everything up as you would if you want to position: absolute inside a position: relative container, and then create a new fixed position div inside the div with position: absolute , but do not set its top and left properties. It will then be fixed wherever you want it, relative to the container.
We can easily change the order of built-in grid columns with push and pull column classes. The Push and Pull Classes: The push class will move columns to the right while the pull class will move columns to the left.
Fixed position is relative to body, so it will count the 100%
width from body width. If using javascript is ok, you can set the sticky width by getting the container width. Check the Updated Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With