首页 > 解决方案 > Flexbox 将几个项目向左对齐,几个向中心对齐,几个向右对齐 - 顺序应该是可变的

问题描述

对于以下情况,我需要一个 CSS 解决方案:

我有几个孩子,比如说四个。并非所有四个孩子的宽度都相同。默认情况下,项目向左对齐。我使用margin-left和/或margin-right自动将项目对齐到中心/右侧。order我使用 CSS属性更改项目的顺序。

现在我想将项目与容器的左侧、中心和右侧对齐。孩子的顺序应该在视口上改变(使用@media查询)。

如何以不同的视口宽度将未指定数量的项目居中到左侧、中心和右侧?

我的(简化的)HTML

<div class="header-container">

 <div class="first-child">
 </div>
 <div class="second-child">
 </div>
 <div class="third-child">
 </div>
 <div class="fourth-child">
 </div>

</div>

我还将我的简化情况放在这个 JSFiddle中。

带有视口的外观的具体示例

@media (max-width: 799px) {*

 left: first-child and second-child

 center: third-child

 right: fourth-child

}

@media (max-width: 800px) and (max-width: 1319px) {

 left: third-child

 center: first-child and second-child

 right: fourth-child

}

@media (min-width: 1320px) {

 left: first-child

 center: third-child

 right: second-child

 fourth-child - display: none;

}

标签: cssflexboxalignment

解决方案


首先,您必须将例如位于中间的孩子分组:

<div class="grouped-items">
  <div class="second-child">
  </div>
  <div class="third-child">
  </div>
</div>

之后,您将拥有三组项目或单独的项目。利用justify-content: space-between

它看起来像这样(在整页中打开以查看最佳结果):

.header-container {
  width: 100%;
  height: 68px;
  background-color: white;
  display: flex;
  justify-content: space-between;
}


/* Set display: flex so they will act same as if they weren't in another div */

.grouped-items {
  display: flex;
}

.first-child {
  width: 60px;
  height: 100%;
  background-color: red;
}

.second-child {
  width: 80px;
  height: 100%;
  background-color: green;
}

.third-child {
  width: 50px;
  height: 100%;
  background-color: blue;
}

.fourth-child {
  width: 100px;
  height: 100%;
  background-color: black;
}

@media (max-width: 799px) {
  .grouped-items {
    order: 1;
  }
  .third-child {
    order: 2;
  }
  .fourth-child {
    order: 3;
  }
}

@media (min-width: 800px) and (max-width: 1319px) {
  .grouped-items {
    order: 2;
  }
  .third-child {
    order: 1;
  }
  .fourth-child {
    order: 3;
  }
}

@media (min-width: 1320px) {
  .fourth-child {
    display: none;
  }

  .grouped-items {
    order: 2;
  }
  .third-child {
    order: 1;
  }
}

body {
  background-color: grey;
  margin: 0;
}
<div class="header-container">

  <div class="grouped-items">
    <div class="first-child">
    </div>
    <div class="second-child">
    </div>
  </div>

  <div class="third-child">
  </div>

  <div class="fourth-child">
  </div>

</div>

要更改媒体上的顺序,只需使用order


推荐阅读