CSS使用flexbox在两侧对齐一些项目 [英] CSS align few items on both side with flexbox

查看:382
本文介绍了CSS使用flexbox在两侧对齐一些项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用CSS flexbox在两边同时做一些项目,但是不知何故我不能并排粘贴它们(div)。

I am trying to do few items on both side by using css flexbox but somehow I just can't stick them (div) side by side.

PS:我无法设置元素数量,因为我希望它具有灵活性,因为我可以添加或删除它,并且不会影响CSS。

PS: I can't set number of elements because I want it to be flexible as in I can add in or remove and it won't affect my css.

我希望它像这样。图片样本:

我已经尝试过了。但是从输出中您可以看到,左侧的div之间存在间隙。

I've tried this. But you can see from the output that there is gap between div on the left side.

.bottom{
  position:fixed;
  bottom:0;
}
.wrapper {
    width: 500px;
    border: solid 1px #000;
    display: flex;
    justify-content: flex-end;
}
.item-left {
    width: 20%;
    border: solid 1px #000;
    margin-right:auto;
}
.item-right {
    width: 20%;
    border: solid 1px #000;
    height: 200px;
}

<div id="bottom" class="bottom">
  <div class="wrapper">
    <a class="item item-left">
      <div class="item-label">Label</div>
    </a>
    <a class="item item-left">
      <div class="item-label">Label</div>
    </a>
    <a class="item item-right">
      <div class="item-label">Label</div>
    </a>
    <a class="item item-right">
      <div class="item-label">Label</div>
    </a>
  </div>
</div>


这是jsFiddle

推荐答案

一个想法是选择 item-right 元素,它是 item-left 的相邻同级元素,并添加 margin-left:自动

One idea is to select the item-right element that's an adjacent sibling of item-left and add margin-left:auto.

请参见相邻的同级组合器

/*
.bottom {
  position: fixed;
  bottom: 0;
}
*/

.wrapper {
  height: 100px;
  display: flex;
  border: solid 1px #000;
  background-color: lightblue;
}

.item {
  background-color: lightgreen;
  border: solid 2px #000;
  flex: 0 0 15%;
}

.item-left {
  border-color: red;
}
.item-right {
  border-color: purple;
}

.item-left + .item-right {
  margin-left: auto;
}

<div id="bottom" class="bottom">
  <div class="wrapper">
    <a class="item item-left">
      <div class="item-label">Left</div>
    </a>
    <a class="item item-left">
      <div class="item-label">Left</div>
    </a>
    <a class="item item-right">
      <div class="item-label">Right</div>
    </a>
    <a class="item item-right">
      <div class="item-label">Right</div>
    </a>
    <a class="item item-right">
      <div class="item-label">Right</div>
    </a>
  </div>
</div>

这篇关于CSS使用flexbox在两侧对齐一些项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆