Question

As I have stated in the title, I'm trying to create a horizontal toolbar with affix in Bootstrap. I don't mind if the toolbar is wrapped in a well, a nav or a panel as long as it's horizontal and uses affix.

I'm currently using a well, I have tried with several Bootstrap components and the result is exact the same.

When my toolbar is NOT in "affixed" state it works fine, it has the appropriate width and so forth but when affix kicks in it lose it's width since position: fixed. As far as I know, elements with fixed position must provide a specific width and that's fine, my problem is that I cannot find an accurate and reliable way of keeping the same width that the toolbar had before being "affixed", which is going to be different with regard to the device resolution.

How could I provide the appropriate width to the "affixed" toolbar? If I don't provide width, the toolbar is too small; if I provide width 100%, the toolbar overflows on the right and some UI elements are missing.

Here is an example that reproduces exact the same problem I'm having: http://www.bootply.com/DAOHegIaTl.

This is the CSS used for the affix:

@media (max-width: 767px) {
  #content-library-toolbar.affix
  {
    top: 100px;
    z-index:1;
  }
}

@media (min-width: 768px) {
  #content-library-toolbar.affix
  {
    top: 50px;
    z-index:1;
  }
}
Was it helpful?

Solution

This is a common problem with fixed elements since CSS position:fixed removes the element from the page flow. The fixed element is no longer relative to it's container and neighboring elements.

In your case, the width of the fixed toolbar element is the problem. You could use jQuery to hook into the affix plugin events. The first event gets the width of the toolbar just before it gets affixed, and the 2nd event sets the width once the toolbar is affixed..

var myWidth;
$('#content-library-toolbar').bind('affix.bs.affix', function () {
  myWidth = $(this).width();
});

$('#content-library-toolbar').bind('affixed.bs.affix', function () {  
  $(this).width(myWidth);
});

Demo: http://www.bootply.com/oc8MgNC2Od

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top