猿问

左,中和右对齐3个不相等的块

我正在尝试对齐包含3个内容块的顶部菜单。


我想要实现的是:


块1:左对齐

块2:水平居中

块3:右对齐

如果所有3个块的大小都相同,则可以使用flexbox(如代码段中所示),但它们不是,所以不会产生我需要的输出。


相反,flexbox在3个块之间放置了相等的空间-导致中间块偏离中心对齐。


我想知道这是否可以使用flexbox来实现,如果不能,则可以采用另一种解决方案。这需要在生产中稳健地工作,因此由于支持不足,因此不适用“网格”解决方案。


.container {

  margin: 20px 0;

}


.row {

  background-color: lime;

  display: flex;

  justify-content: space-between;

}


.item {

  background-color: blue;

  color: #fff;

  padding: 16px;

}

<div class="container">

  <div class="row">

    <div class="item">left, slightly longer</div>

    <div class="item">center, this item is much longer</div>

    <div class="item">right</div>

  </div>

</div>


一只萌萌小番薯
浏览 550回答 2
2回答

jeck猫

您可以考虑flex-grow:1;flex-basis:0%使用left和right元素,然后text-align在其中对齐内容。我添加了一个额外的包装程序,以仅在文本周围保留背景。诀窍是通过仅删除中间内容并将其均分为左元素和右元素来计算可用空间。.container {&nbsp; margin: 20px 0;&nbsp; padding-top:10px;&nbsp; background:linear-gradient(#000,#000) center/5px 100% no-repeat; /*the center*/}.row {&nbsp; background-color: lime;&nbsp; display: flex;&nbsp; color: #fff;}.item:not(:nth-child(2)) {&nbsp; flex-basis: 0%;&nbsp; flex-grow: 1;}.item:last-child {&nbsp; text-align: right;}.item span{&nbsp; background-color: blue;&nbsp; display:inline-block;&nbsp; padding: 16px;&nbsp; height:100%;&nbsp; box-sizing:border-box;}<div class="container">&nbsp; <div class="row">&nbsp; &nbsp; <div class="item"><span>left, slightly longer</span></div>&nbsp; &nbsp; <div class="item"><span>center, this item is much longer</span></div>&nbsp; &nbsp; <div class="item"><span>right</span></div>&nbsp; </div></div>您也可以通过使元素保持关闭来执行相同的操作。只需调整文本对齐即可:.container {&nbsp; margin: 20px 0;&nbsp; padding-top:10px;&nbsp; background:linear-gradient(#000,#000) center/5px 100% no-repeat; /*the center*/}.row {&nbsp; background-color: lime;&nbsp; display: flex;&nbsp; color: #fff;}.item:not(:nth-child(2)) {&nbsp; flex-basis: 0%;&nbsp; flex-grow: 1;}.item:first-child {&nbsp; text-align: right;}.item span{&nbsp; background-color: blue;&nbsp; display:inline-block;&nbsp; padding: 16px;&nbsp; height:100%;&nbsp; box-sizing:border-box;}<div class="container">&nbsp; <div class="row">&nbsp; &nbsp; <div class="item"><span>left, slightly longer</span></div>&nbsp; &nbsp; <div class="item"><span>center, this item is much longer</span></div>&nbsp; &nbsp; <div class="item"><span>right</span></div>&nbsp; </div></div>

慕的地8271018

您能否给flex-grow:1作为商品类别并检查.item {background-color: blue;color: #fff;padding: 16px;flex-grow:1;}希望这是您要寻找的
随时随地看视频慕课网APP
我要回答