19

As it was already answered (How can I have a position: fixed; behaviour for a flexbox sized element?) absolutely/fixed positioned boxes are taken out of the normal flow of Flexbox-aligned elements. But how can I at least simulate position: fixed behavior of, say, width: 300px; height: 100vw element?

Here is a demo (http://codepen.io/anon/pen/ZGmmzR) of initial layout with sidebar on the left and content block on the right. I would like nav act like position: fixed element following user's scroll across the page. I know how to do it without Flexbox. In the first place I would consider pure CSS solution without using JavaScript. Thank you!

Community
  • 1
  • 1
user3576508
  • 613
  • 1
  • 4
  • 12

1 Answers1

45

Edit:

A solution that somehow feels less hacky could be to make the container (.wrapper) as tall as the screen, and only add scrolling to the main <section> element:

.wrapper {
    display: flex;
    height: 100vh;
}

section {
    flex: 1 1 auto;
    overflow: auto;
}

http://codepen.io/Sphinxxxx/pen/WjwbEO

Original answer:

You could simply put everything inside <nav> in a wrapper (here: nav-wrapper), and then fix that wrapper:

...
.nav-wrapper {
    position: fixed;
    top: 0; left: 0;
}

<nav role="navigation">
    <div class="nav-wrapper">
        ...
    </div>
</nav>

http://codepen.io/anon/pen/PqXYGM

Sphinxxx
  • 12,484
  • 4
  • 54
  • 84
  • 3
    This is very correct and obvious solution. I should really have some rest next time before working. Thank you! – user3576508 Jul 31 '15 at 19:12
  • This will only work if the nav is at one of the edges, because `position: fixed` positions relative to the _viewport_. So this won't help if, like me, you're trying to fix a nav inside a centered flex container. – Vicky Chijwani Mar 07 '17 at 15:09
  • @VickyChijwani - What would that layout look like? Do you have a demo? – Sphinxxx Mar 07 '17 at 15:29
  • @Sphinxxx sorry, I don't have a demo. But I ultimately went with an edge-positioned fixed div anyway; ran out of alternatives. – Vicky Chijwani Mar 08 '17 at 09:46
  • @SudarP - I don't have a Safari browser, but it's just basic [flexbox](https://caniuse.com/#feat=flexbox) behavior, so I assume it does. – Sphinxxx Jun 11 '18 at 23:33
  • 1
    Flex solution works but with overflow property the content scrolling position is broken on refresh (position not remembered). – Burrich Jul 25 '18 at 10:06
  • 1
    @Burrich I used a flex layout similar to the edited solution in this answer. css-tricks.com references a simple JavaScript and local storage solution from a Twitter post (https://twitter.com/hakimel/status/1262337065670316033) for the remembering the scroll position of a sidebar div (or any div). https://css-tricks.com/memorize-scroll-position-across-page-loads/. See the reader comments for recommended modifications to the code in the tweet. – Dave B Feb 23 '21 at 21:48