简体   繁体   中英

Center a nav item (or logo) responsive in the middle of a navbar

I can't seem to find an elegant and responsive way to auto position a 'logo' in the center of a navbar consider more items could be added or removed, and it would make much more sense than fixed margin numbers (as I know I could do it that way).

The design is simple (built in Gatsby):

 nav { display: flex; margin: 0 auto; max-width: 600px; } a { margin-right: 20px; } .logo { margin: 0 auto; } 
 <nav> <a>Item 1</a> <a>Item 2</a> <a>Item 3</a> <a class="logo">Logo</a> <a>Item 4</a> </nav> 

I'm not sure how to approach this problem without, as mentioned before, fixing margin number (ie 10px left 22px right) with the combination of media queries.

Anyone have any solutions?

One solution might be to group your nav into 3 different sections, left, center and right. Then use flex box to position these, but give them a min and max of a 3rd of a page. Also, you will need to center your logo and right align your right column.

Probably a more robust solution is to use CSS grid. Same sort of idea where divide your page into 3 columns, but you can set your 3 columns widths to 1fr, instead of giving a min and max width of 33.333333...% - This is far more elegant solution, I think. I've provided an example of this too.

 nav { display: flex; justify-content: flex-start; } nav>div { max-width: 33.3333%; min-width: 33.3333%; } .logo { text-align: center; } .right { text-align: right; } .grid { display: grid; grid-template-columns: repeat(3, 1fr); } .grid-left { grid-column: 1 / 2; background-color: darkseagreen; } .grid-center { grid-column: 2 / 3; background-color: coral; text-align: center; } .grid-right { grid-column: 3 / 4; background-color: steelblue; text-align: right; } 
 <h2>Flex example</h2> <nav> <div> <a>Item 1</a> <a>Item 2</a> <a>Item 3</a> </div> <div class="logo"> <a>Logo</a> </div> <div class="right"> <a>Item 4</a> </div> </nav> <h2>Grid example</h2> <div class="grid"> <div class="grid-left"> <a>Item 1</a> <a>Item 2</a> <a>Item 3</a> <a>Item 4</a> <a>Item 5</a> </div> <div class="grid-center"> <a class="logo">Logo</a> </div> <div class="grid-right"> <a>Item 4</a> </div> </div> 

Whenever I need to center something I usually default to a simple absolute position. This method is a life-saver when it comes to vertical centering as well!

nav {
   position: relative;
   max-width: 600px;
}
.logo {
   position: absolute;
   left: 50%;
   transform: translateX(-50%);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM