cssflexboxvertical-alignmentnav

Difficulty centering <nav> vertically in flexbox


Here's the relevant code. I need to align the nav menu vertically in the green area (.menu-box). I can only seem to center it horizontally. What am I missing? (I tried vertical-align: middle; but to no effect. I have tried various combinations of display: and flex-flow: but have not found one that works.

<!doctype html>
<html>
    <head>
        <style>
            .header-box {
                flex-flow: column wrap;
                display: inline-flex;
                background-color: beige;
                width: 100%;
                height: 100px;
                column-gap: 0px;
            }
    
            .logo-box {
                background-color: pink;
                height: 100%;
                width: 25%;
                align-content: flex-start;
                min-width: 85px;
            }
    
            .logo-box p {
                flex-flow: column nowrap;
                font-size: 23px;
            }
    
            .menu-box {
                background-color: green;
                width: 50%;
                height: 100%;
                text-align: center;
            }
    
            .menu-box nav {
                font-size: 23px;
                background-color: yellow;
            }
    
            .dummy-box {
                background-color: red;
                width: 25%;
                height: 100%;
            }
        </style>
    </head>
    
    <body>
        <span class="header-box">
    
            <span class="logo-box">
            </span>
    
            <span class="menu-box">
                <nav>
                    <a href="/html/">Home</a> |
                    <a href="/css/">Menu</a> |
                    <a href="/js/">Gallery</a> |
                    <a href="/python/">About</a>
                </nav>
            </span>
    
            <span class="dummy-box">
            </span>
        </span>
    </body>
</html>

Solution

  • Did you tried add the flex inside the .menu-box?

    .menu-box {
        background-color: green;
        width: 50%;
        height: 100%;
        display: flex;
        align-items: center;
    }
    

    This will make the nav menu flex container and vertically align its child elements (in this case, the <nav> element) to the center.

    With these changes, the nav menu should now be vertically centered within the green area .menu-box. Adjust the justify-content property to control the spacing between the nav items. If you need, you can include justify-content: space-around in the .menu-box