Search code examples
htmlcssflexboxalignmentnavbar

How to place only certain items in a flexbox to the right?


My navbar has 5 items and I'd like to place only two of them to the right - so they'd look as if they were 'aligned' to the right. I tried it with the margin-left: auto; rule inside the .right rule block, but that didn't quite work. How should I approach this problem?

* {
    box-sizing: border-box;
    margin: 0;
    padding:0
}

#flex-nav {
    display: flex;
    flex-direction: row;
    align-items: center;
}

.right {
    margin-left: auto;
}
        <div id='flex-nav'>
            <a href='#'>Home</a>
            <a href='#'>News</a>
            <a href='#'>About</a>
            <a class='right' href='#'>Sign-in</a>
            <a class='right' href='#'>Sign-up</a>
        </div>


Solution

  • You only need to apply the right class to the first one to be pushed over.

    * {
        box-sizing: border-box;
        margin: 0;
        padding:0
    }
    
    #flex-nav {
        display: flex;
        flex-direction: row;
        align-items: center;
    }
    
    .right {
        margin-left: auto;
    }
            <div id='flex-nav'>
                <a href='#'>Home</a>
                <a href='#'>News</a>
                <a href='#'>About</a>
                <a class='right' href='#'>Sign-in</a>
                <a href='#'>Sign-up</a>
            </div>