How can I have a position: fixed; behaviour for a flexbox sized element?

Daniel Schmidt picture Daniel Schmidt · Mar 13, 2015 · Viewed 85.3k times · Source

I have a div called .side-el which I would like to have in a position: fixed; behavior, but as soon as I apply position fixed the width alternates from the right one. The right width would be the one set by flexbox. How can I achieve this goal?

Answer

Wylliam Judd picture Wylliam Judd · Aug 28, 2017

Here's a way to do this inspired by bootstrap:

.fixed-top {
  display: flex;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

This gives your flex-box room to breathe and do it's flex-box thing. If your flex-direction is column, you could use top, left, bottom instead.

This works because when you give an element a fixed position and a left and right of 0 or a top and bottom of 0, the element is stretched to fill the space from left to right, or top to bottom. That in turn allows a flex-box to use the amount of space you would expect without position fixed.