Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

CSS CSS Flexbox Layout Building a Layout with Flexbox Creating a Sticky Footer with Flexbox

Can we create a sticky header with navigation just like relative and absolute position using flexbox method?

In CSS basic course, we created sticky header with absolute and relative positioning and adding z-index if images overflow the header. Is it possible to create similar design with flexbox model?

2 Answers

Yes! Here is a basic example of a sticky header that uses flexbox:

<style>
    body {
        margin: 0;
        padding: 0;
    }

    .header {
        position: fixed;
        display: block;
        width: 100%;
        background: red;
        z-index: 1000;
    }

    @media screen and (min-width: 590px) {
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
    }

    .logo {
        width: 175px;
        height: 65px;
        margin: 10px auto;
        background: black;
    }

    @media screen and (min-width: 590px) {
        .logo {
            margin-left: 10px;
        }
    }

    .nav {
        margin: 0 auto;
        padding-bottom: 10px;
        font-family: sans-serif;
        font-size: 14pt;
        text-transform: uppercase;
        text-align: center;
    }

    @media screen and (min-width: 590px) {
        .nav {
            margin-right: 25px;
            padding-bottom: 0;
        }
    }

    .nav-item {
        padding: 5px;
        color: black;
        text-decoration: none;
    }

    .nav-item:hover {
        color: white;
    }
</style>
<header class="header">
    <div class="logo"></div>
    <nav class="nav">
        <a class="nav-item" href="">home</a> |
        <a class="nav-item" href="">about</a> |
        <a class="nav-item" href="">work</a> |
        <a class="nav-item" href="">contact</a>
    </nav>
</header>

Check out this link for all the great options flexbox includes: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

I hope this answers your question!

Thanks John. I will try to mess around with this code and see if everything is fluid. :)