Flexbox: centered element with space-around elements on either side

前端 未结 2 1279
萌比男神i
萌比男神i 2021-02-01 05:50

I\'m using flexbox to set up a menu consisting of seven

  • elements with various widths. I\'d like my middle (4th in the source order)
  • 相关标签:
    2条回答
    • 2021-02-01 06:11

      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

      0 讨论(0)
    • 2021-02-01 06:13

      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

      0 讨论(0)
    提交回复
    热议问题