Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate 'position:fixed' behavior on Flexbox-aligned sidebar

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!

like image 575
user3576508 Avatar asked Jul 30 '15 04:07

user3576508


People also ask

Does flexbox work with position fixed?

position:fixed makes flexbox not workable, since it overrides the position of <p>Hello</p> Try to remove it and see the difference. If you want align-items:center works; try to set height: 100vh; since the body height of webview is not set to screen height by default.

How do you align items right in flexbox?

Alignment and flex-direction In a left to right language the items all line up on the left. Try changing flex-direction: row-reverse to flex-direction: row . You will see that the items now move to the right-hand side.

How do you center a fixed element position?

You basically need to set top and left to 50% to center the left-top corner of the div. You also need to set the margin-top and margin-left to the negative half of the div's height and width to shift the center towards the middle of the div.


1 Answers

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

like image 111
Sphinxxx Avatar answered Jan 02 '23 03:01

Sphinxxx