Bootstrap - maintaining column widths using position: fixed?

I am trying to create a sticky navigation on my page where the div gets position:fixed; after the user scrolls the item. Functionality works as expected, but the width of the two columns that should adhere to the top change after adding the sticky class. I tried to add width:100%; in the CSS of the sticky element, but then the element expands outside the container.

How can I make sure that the width of the columns remains where they should be when position:fixed; ?

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(); 

Jsfiddle

Thanks!

+5
source share
4 answers

A fixed position relative to the body, so it will consider the width of 100% of the width of the body. If javascript is used in order, you can set the sticky width by getting the width of the container. Check Updated Script

+3
source

add:

 width:inherit; 

to your .sticky.stick

Jsfiddle

as Nanang Mahden El-Agun said, a fixed position connects the width with the body. Using width:inherit; it will use the width of the .container class

reference: Set the position width of the "fixed: fixed" div relative to the parent div

+2
source

I managed to get it to work by installing the container in a "container-liquid", then adding the width: 100%; to your .stick class.

+1
source

You can add a wrapper to the 100% width of the container and use this stick instead.

 <div class="wrap"> <div class="container sticky"> <div class="row"> ... </div> </div> </div> 

updated fiddle: https://jsfiddle.net/mileandra/omeegfc7/

+1
source

All Articles