Scroll only a portion of the screen with flexbox

So far I am finding that flexbox does indeed work well for positioning and sizing items within the viewport.  I like its approach when we are creating an app rather than a document, and of course this usually is the case with Angular.  Here is an example.

A perfect scrollbar

Do you have content you want to stay at the top of the window instead of scroll away?  This means you have to take control of your content sizing such that the operating system’s native scrollbar for the window never appears.  This comes naturally to flexbox.  When there is only one flex item it takes all of the space – all of the remaining space, to be precise.  So use two div’s, with just the second one designated flex.  The first div will stay fixed at the top.  The second div will scroll.  There will be no wasted space, and no double scrollbars.  Here it is in pure HTML/CSS:

<html>
<body>
<div style="display:flex;
  flex-flow:column;
  height:100%">
  <div>my fixed content</div>
  <div style="flex:1;overflow-y:auto;">
    <p>my scrolling content</p>
    ... lots of content here ...
  </div>
</div>
</body>
</html>

In Angular we can use the flex-layout module to express the div tags more concisely:

<div fxLayout="column" style="height:100%">
  <div>my fixed content</div>
  <div fxFlex style="overflow-y:auto">
    <p>my scrolling content</p>
    ... lots of content here ...
  </div>
</div>

Here is an image of the results I get using this technique in my Shufflizer app:

[14-May-2018 For some reason, in Shufflizer I had to specify 100vh instead of 100%.  Using 100% resulted in simple whole app scrolling.  Using vh instead solved it except eventually I noticed a problem in MicroSoft Edge – div’s overlapped as if they didn’t know about each other, all starting at the top of the viewport.  So I went back to the pure HTML/CSS way, but using vh instead of %.  That worked in all the browsers I am testing (FireFox, Edge, Chrome).]

Leave a Reply

Your email address will not be published. Required fields are marked *