Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap - maintaining column widths using position:fixed?

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

JSFiddle

Thanks!

like image 770
user13286 Avatar asked Jul 15 '15 15:07

user13286


People also ask

Does position fixed affect width?

it does not work. with position: fixed the element is out of the normal flow and it doesn't respect it's parent width.

How do I change the width of a column in bootstrap?

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.

How do I keep my div position fixed?

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.

How do I change the position of a column in bootstrap?

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.


1 Answers

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

like image 82
Nanang Mahdaen El-Agung Avatar answered Sep 18 '22 12:09

Nanang Mahdaen El-Agung