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

前端 未结 2 1280
萌比男神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: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.

      
      

      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

    提交回复
    热议问题