Flexbox在左边对齐多个项目,在中心对齐一些,在右边对齐-顺序应可更改

问题描述 投票:-1回答:1

我在以下情况下需要CSS解决方案:

我有几个孩子的头,比如四个。并非所有四个孩子的宽度都相等。我已将简化的情况放在this JSFiddle中。

在我当前的情况下,默认情况下项目左对齐。我使用margin-left和/或margin-right自动将项目对齐到中心/右侧。我使用CSSorder-propery更改了项目的顺序。

现在,我要将项目对齐到容器的左侧,中央和右侧。顺序应该可以在三个不同的视口(使用@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>

有问题的具体示例:

**@media (max-width: 799px) the order should be:**

left: first-child and second-child

center: third-child

right: fourth-child

**@media (min-width: 800px) and (max-width: 1319px) the order should be:**

left: third-child

center: first-child and second-child

right: fourth-child

**@media (min-width: 1320px) the order should be:**

left: first-child

center: third-child

right: second-child

fourth-child - display: none;
css flexbox alignment
1个回答
0
投票

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

<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

© www.soinside.com 2019 - 2024. All rights reserved.