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 lucamauri.com and I recently replicated it with my new project passafrase.it, 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="https://github.com/lucamauri/PassaFrase">
    <img style="position: absolute; top: 0; right: 0; border: 0;z-index:100;" src="https://camo.githubusercontent.com/52760788cde945287fbb584134c4cbc2bc36f904/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f77686974655f6666666666662e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png" />
</a>

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.

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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