Making a vertical Grid navbar become fixed

Making a vertical Grid navbar become fixed
0

#1

I’m finishing up my technical documentation page: https://codepen.io/Crimson_Macaw/full/bjYVJm/ using css grid and cannot get my vertical navigation bar on the side to become fixed when I scroll down. Adding position:fixed won’t work since it completely messes up the display. I’d appreciate any and all help.


#2

Fiddled around with this problem some time ago
and I decided, that a Grid isn’t that useful for this case.

I think a Grid makes much sense for 2D ordering.
Your page only has 1D: the navbar on the left side and the main content on the right side.

I think, that a simple Flexbox with flex-direction row for the body will do the trick.
And the navbar and the main can use both a flexbox with flex-direction column,

For the responsive layout, you can change the page to a single column layout by changing the body to a flex-direction column.


#3

position: fixed and position: absolute take elements out of the normal document flow, just like floats. So when you are applying position: fixed to the side bar, the grid is basically under the impression that the side bar no longer exists. It’s been taken out of the document flow, so the grid then moves the next element the the first position (moving your main documentation area to the first column which is 240px wide).

If you really still want to use grid for this, you will need to specify that the main documentation area is in the second column, and you will also need to apply a fixed-width to the sidebar, since one again, it is taken out of the document flow so it is not part of the grid. If you really want the side bar to be fixed, grid doesn’t make much sense to be honest, since the only thing that will end up being part of the grid is the documentation section.

If you don’t 100% NEED it to be fixed to the top and it’s just a nice-to-have, you could look into position: sticky. It doesn’t have full browser support, so you could consider it progressive enhancement for browsers that do support it.


#4

@mewmew I’ve changed the css to make it work without grid (thanks to @Tchoukoualeu for the help), but just out of curiosity how exactly would I specify that the second column should be the main documentation area?


#5

You could do this in two ways:

Specifying the column on the element:

.element {
 grid-column: start / end; 
}

Start should be the grid column line to start at, which in this case is 2; end is the grid column line where it should end. in this case, it could be omitted since there are just two columns, so for your case, it would be:

grid-column: 2;

you could also use grid areas.

On your grid container, you could do:

grid-template-areas: "sidebar maindoc" ;

Then on your grid item (the main documentation area), you could do:

grid-area: maindoc;

Rachel Andrew’s Grid By Example is an excellent learning resource for grid, with short digesttable videos.