简体   繁体   中英

Bootstrap affix- keep sidebar within container when position:fixed

I'm working on implementing a sticky sidebar using Bootstrap's affix plugin. The sidebar sticks as expected, but i am having trouble keeping the div within a padded container. When the affix class is applied, the sidebar will jump outside of the container and all the way to the right side of my browser window.

Is there a simple way to keep the sidebar in its correct place?

See demo:

http://bit.ly/1F56C2C

I followed anpsmn's suggestion but made the following changes:

$('#sidebar').on('affix.bs.affix', function(){ 
    var size = $(window).width(); //get browser width
    var divWidth = $(myContainer).width(); //get width of container
    var margin = (size - divWidth) / 2; //get difference and divide by 2
    $("#sidebar").css("right",margin);
})
.on('affix-top.bs.affix', function () {
  $("#sidebar").css("right","0px");
});

This calculates the amount of space outside of the container as it relates to the browser size. It needs some tweaking but it should work.

You can use Bootstrap events affix.bs.affix and affix-top.bs.affix to set value of right .

We can add the .container 's margin-right and padding-right and set the right value of the #sidebar

$('#sidebar')
  .on('affix.bs.affix', function () {
    var margin =  parseInt($('.container').css("margin-right"));
    var padding = parseInt($('.container').css("padding-right"));
    $("#sidebar").css("right",margin+padding);
  })
  .on('affix-top.bs.affix', function () {
    $("#sidebar").css("right","0px");
  });

Made a slight adjustment sl1983 suggestion which has worked for me:

$('#sidebar').on('affix.bs.affix', function(){ 
    var size = $(window).width(); //get browser width
    var divWidth = $(myContainer).width(); //get width of container
    var margin = (size - divWidth) / 2; //get difference and divide by 2
    var sidebarWidth = $('#sidebar').width(); //get sidebar width

    $("#sidebar").css("right",margin);
    $("#sidebar1").css("width",sidebarWidth);
})
.on('affix-top.bs.affix', function () {
  $("#sidebar").css("right","0px");
});

This will also insure that the sidebar preserves its width when it becomes in a "fixed" state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM