Domanda

I'm using flexbox to set up a menu consisting of seven <li> elements with various widths. I'd like my middle (4th in the source order) <li> element to always be horizontally centered as a sort of anchor, with the 1-3rd <li> elements occupying the space to the left of the centered <li> and the 5th-7th occupying the space to the right.

enter image description here

I've tried space-around, space-between on the parent flex container as well as align-self: center on the <li> element I'm trying to center, but so far no luck. Any help from someone knowledgeable in flexbox would be appreciated.

jsfiddle

È stato utile?

Soluzione

You need to modify your nav structure and start from 3 containers left, center and right. DEMO


HTML

left and right will hold a few links, center is a link.

<nav>
<span>
    <a href="#">aaa </a>
    <a href="#">aa </a>
    <a href="#">a </a>
    </span>
    <a href="#"> center </a>
    <span>
      <a href="#">bbbb </a>
      <a href="#">bbbbb </a>
      <a href="#">bbbbbb </a>
    </span>
</nav>

CSS

nav will take display:flex and justify-content:space-between, so will left and right.

nav, nav span {
    display:flex;
    justify-content:space-between;
    flex-wrap:wrap;/* so they do not overlap each other if space too short */
}

To generate a gap at edges of right and left towards center, we just add a pseudo element (or an empty element).

span:first-of-type:after,
span:last-of-type:before{
    content:'';
    display:inline-block;/* enough , no width needed , it will still generate a space between */
}

left and right can take a flex value higher than 1 , to avoid center to expand too much.

nav > span {
    flex:2; /* 2 is minimum but plenty enough here  */
}

lets draw our link boxes :

a {
    padding:0 0.25em;
    border:solid;
}

DEMO

Altri suggerimenti

I think the way to do this is to split the items into three different ul elements, and then use the flex property to set how large the three columns are.

The outside columns have three elements in them, so they get flex:3. The centered column only has one element, so it gets flex:1. That way, when you resize, flexbox will use 3 flex units for the larger columns, and 1 flex unit for the centered column. If you need to use a different number of items in any of the columns, just change the flex unit to reflect how many items are inside it.

Working fiddle: jsfiddle

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top