Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use position fixed in flex layout?

Tags:

html

css

flexbox

I have a flexbox layout with two columns.

The left column be fixed, while the right is scrollable.

How can you do that?

Take a look at the following code:

#parent {
  display: flex;
}
#left {
  flex-grow: 1;
}
#left div {
  position: fixed;
  background: blue;
  top: 0;
  left: 0;
  height: 100vh;
}
#right {
  flex-grow: 5;
  background: red;
  height: 300vh;
}
<div id="parent">
  <div class="child" id ="left">
    <div>
      ABC
    </div>
  </div>
  <div class="child" id ="right">
  DEF
  </div>
</div>

Fiddle

like image 238
heroxav Avatar asked Dec 31 '16 15:12

heroxav


People also ask

Does Flex work with position fixed?

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.

How do I set my flex position?

Flex Start positions element at the start of the page. Flex End sets the element to the end of the page. Space Around arranges the items evenly but with spaces between them. The spaces will be equal among all the elements inside a flex-box container, but not outside them.

How do you fix fixed positions?

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.

Why position fixed does not work?

Position fixed doesn't work with transform CSS property. It happens because transform creates a new coordinate system and your position: fixed element becomes fixed to that transformed element. To fix the problem you can remove transform CSS property from the parent element.


1 Answers

If I understand your requirements, you want make the right scroll and the left be fixed. That can be done without the use of fixed position.

I would also personally recommend to not use fixed position, unless it is absolutely necessary, as it can have some unwanted behavior on mobile device, and you kind of loose the benefit non positioned solutions like flexbox offer.

html, body {
  margin: 0;
}
#parent {
  display: flex;
  height: 100vh;
}
#left {
  flex-grow: 1;
  background: blue;
}
#right {
  flex-grow: 5;
  background: red;
  overflow: auto;
}
#right div {
  height: 300vh;
}
<div id="parent">
  <div class="child" id ="left">
      ABC
  </div>
  <div class="child" id ="right">
    <div>
      DEF
    </div>
  </div>
</div>
like image 160
Asons Avatar answered Sep 22 '22 10:09

Asons