Stick on top

For several of my web projects I align myself to one of the common non-written rules of web design: make the top bar a menu bar and keep it on top of the browser screen even when you scroll.

I did so for my personal website and I recently replicated it with my new project, so I thought about writing a quick post to summarize how to achieve so.

First of all, I start by modifying the body of the page in CSS file:

body {
    background-color: #1d1c22;
    margin: 0;
    font-family: 'Open Sans', sans-serif;
    font-weight: 400;
    color: white;
    margin-top: 60px;

Clearly, the very important part of this code fragment is the margin-top: 60px; part where I told the browser to shift the whole body of the page 60 pixel down.
Next step is to create the container for the menu: it will be a <div> element with the following style:

#containertopmenu {
    background-color: #4a4a4a;
    position: fixed;
    margin-top: -60px;
    height: 60px;
    z-index: 90;

So I am making it 60 pixel tall and shift it the same 60 pixels up: the end of the process is that body is down by 60 pixel and the same space if filled by this div element.
Note that the z-index: 90; part of the directive assures the top menu DIV will stay on top of other elements of the page.
If anything else should stay on top of it then you should increase or decrease the z-index accordingly.
For instance in this case I added the GitHub ribbon to the upper right corner of the page with the following code

<a href="">
    <img style="position: absolute; top: 0; right: 0; border: 0;z-index:100;" src="" alt="Fork me on GitHub" data-canonical-src="" />

Note that z-index is set to 100 so it stays on top of the menu div that, on turn, is on top of everything else.

Author: lucamauri

First and foremost a geek and a Trekker, Luca Mauri is employed as an IT Manager. A Space Exploration enthusiast, avid reader and hobbyist photographer.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s