Align 3 unequal blocks left, center and right

前端 未结 4 1149
春和景丽
春和景丽 2020-11-22 06:18

I\'m trying to align a top menu which consists of 3 blocks of content.

What I\'m trying to achieve is this:

  • block 1: left aligned
  • block 2: cen
4条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 07:01

    You can consider flex-grow:1;flex-basis:0% for the left and right elements then use text-align to align content inside. I have added an extra wrapper to keep the background only around the text.

    The trick is to calculate the free space by removing only the middle content and split it equally to the left and right element.

    .container {
      margin: 20px 0;
      padding-top:10px;
      background:linear-gradient(#000,#000) center/5px 100% no-repeat; /*the center*/
    }
    
    .row {
      background-color: lime;
      display: flex;
      color: #fff;
    }
    
    .item:not(:nth-child(2)) {
      flex-basis: 0%;
      flex-grow: 1;
    }
    
    .item:last-child {
      text-align: right;
    }
    
    .item span{
      background-color: blue;
      display:inline-block;
      padding: 16px;
      height:100%;
      box-sizing:border-box;
    }
    left, slightly longer
    center, this item is much longer
    right

    You can also do the same by keeping the element close. Simply adjust text-align:

    .container {
      margin: 20px 0;
      padding-top:10px;
      background:linear-gradient(#000,#000) center/5px 100% no-repeat; /*the center*/
    }
    
    .row {
      background-color: lime;
      display: flex;
      color: #fff;
    }
    
    .item:not(:nth-child(2)) {
      flex-basis: 0%;
      flex-grow: 1;
    }
    
    .item:first-child {
      text-align: right;
    }
    
    .item span{
      background-color: blue;
      display:inline-block;
      padding: 16px;
      height:100%;
      box-sizing:border-box;
    }
    left, slightly longer
    center, this item is much longer
    right

提交回复
热议问题