如何在显示器flex的中心位置放置一个元素

时间:2017-08-08 16:41:57

标签: css css3 flexbox

我有div elemenents的容器

.container {
  display: flex;
  justify-content: space-between;
}

如何使一个元素位于此块的中心,而其他元素位于space-between

.container {
  display: flex;
  justify-content: space-between;
}

.container div {
  height: 50px;
}

.one,
.four,
.seven {
  background-color: red;
  width: 200px;
}

.two,
.six {
  background-color: green;
  width: 100px;
}

.three,
.five {
  background-color: yellow;
  width: 150px;
}

.center {
  width: 300px;
  background-color: black;
}
<div class="container">
  <div class="one"></div>
  <div class="two"></div>
  <div class="three"></div>
  <div class="center"></div>
  <div class="four"></div>
  <div class="five"></div>
  <div class="six"></div>
  <div class="seven"></div>
</div>

jsFiddle

1 个答案:

答案 0 :(得分:2)

根据您希望的动态程度,这里有一个建议,即center元素左侧和右侧的项目都会被包装。

leftright每个减去50%减去center的宽度(每边150px),这将center放在中间。< / p>

Updated fiddle

Stack snippet

.container {
  display: flex;
  justify-content: space-between;
}

.container div {
  height: 50px;
}

.left, .right {
  display: flex;
  justify-content: space-between;
  flex-basis: calc(50% - 150px);
}

.one,
.four,
.seven {
  background-color: red;
  flex-basis: 200px;
}

.two,
.six {
  background-color: green;
  flex-basis: 100px;
}

.three,
.five {
  background-color: yellow;
  flex-basis: 150px;
}

.center {
  flex-basis: 300px;
  background-color: black;
}
<div class="container">

  <div class="left">
    <div class="one">
    </div>
    <div class="two">
    </div>
    <div class="three">
    </div>
  </div>

  <div class="center">
  </div>

  <div class="right">
    <div class="four">
    </div>
    <div class="five">
    </div>
    <div class="six">
    </div>
    <div class="seven">
    </div>
  </div>

</div>

通过向每个侧包装器添加一个伪,我们也可以使它的行为类似于space-between在没有包装器的情况下的工作方式(尽管仍然以center为中心)。

在这个fiddle demo(以及Stack片段下方)中,我更改了宽度,以便更容易看到它在全屏幕中的表现。

.container {
  display: flex;
  justify-content: space-between;
}

.container div {
  height: 50px;
}

.left, .right {
  display: flex;
  justify-content: space-between;
  flex-basis: calc(50% - 100px);
}

.left::after,
.right::before {
  content: '';
}

.one,
.four,
.seven {
  background-color: red;
  flex-basis: 125px;
}

.two,
.six {
  background-color: green;
  flex-basis: 25px;
}

.three,
.five {
  background-color: yellow;
  flex-basis: 75px;
}

.center {
  flex-basis: 200px;
  background-color: black;
}
<div class="container">

  <div class="left">
    <div class="one">
    </div>
    <div class="two">
    </div>
    <div class="three">
    </div>
  </div>

  <div class="center">
  </div>

  <div class="right">
    <div class="four">
    </div>
    <div class="five">
    </div>
    <div class="six">
    </div>
    <div class="seven">
    </div>
  </div>

</div>