如何将1个项目发送到最后,而其余项目在Flexbox容器中居中

时间:2018-03-30 03:06:08

标签: html css flexbox

使用flexbox容器,如何让第一个孩子居中,第二个孩子到底?我尝试了以下但是没有用:

.flexbox {
  display: flex;
  justify-content: center;
  height: 200px;
}

.box1 {
  width: 100px;
}

.box2 {
  width: 100px;
  justify-self: end; /* does nothing */
}

div{ border: 1px solid black; } /* to help see the divs */
<div class="flexbox">
  <div class="box1"></div>
  <div class="box2"></div>
</div>

5 个答案:

答案 0 :(得分:2)

Justify-self仅适用于grid而不是flexbox

&#13;
&#13;
.flexbox {
  display: grid;
  grid-template-columns: auto auto;
  height: 200px;
  width: 500px;
  background: orange;
}

.box1 {
  width: 100px;
  height: 200px; 
  background: red;
  justify-self: end;
}

.box2 {
  width: 100px;
  justify-self: end;
  height: 200px; 
  background: blue;
}
&#13;
<div class="flexbox">
  <div class="box1"></div>
  <div class="box2"></div>
</div>
&#13;
&#13;
&#13;

但是对于您的问题,您可以使用absolute定位

解决问题

&#13;
&#13;
.flexbox {
  position: relative;
  display: flex;
  justify-content: center;
  height: 200px;
  width: 500px;
  background: orange;
}

.box1 {
  width: 100px;
  height: 200px;
  background: red;
}

.box2 {
  position: absolute;
  width: 100px;
  height: 200px;
  background: blue;
  top: 0;
  right: 0;
}
&#13;
<div class="flexbox">
  <div class="box1"></div>
  <div class="box2"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以制作一个不可见的第一个盒子,然后使用flex:space-between。这是我如何做到的。

&#13;
&#13;
.flexbox {
  display: flex;
  justify-content: space-between;
  height: 200px;
}

.flexbox-again {
  display: flex;
  justify-content: flex-end;
  height: 200px;
}

.box0 {
  width: 100px;
  background: none;
}

.box1 {
  width: 100px;
  background: blue;
}

.box2 {
  background: red;
  width: 100px;
  justify-self: end; // does nothing
}
&#13;
<div class="flexbox">
  <div class="box0"></div>
  <div class="box1"></div>
  <div class="box2"></div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用align-self属性。它会起作用

.box2 {
     width: 100px;
     align-self: flex-end;
}

答案 3 :(得分:0)

你可以试试这个:

&#13;
&#13;
.flexbox {
  display: flex;
  justify-content: space-between;
  height: 200px;
}

.box1 {
  width: 100px;
  background: blue;
}

.box2 {
  width: 100px;
  background: red;
}
/* a third hidden element */
.flexbox:before {
  content: "";
  width: 100px;
}
&#13;
<div class="flexbox">
  <div class="box1"></div>
  <div class="box2"></div>
</div>
&#13;
&#13;
&#13;

答案 4 :(得分:-1)

您可以使用margin-left: 50%;对第一个元素进行居中,然后使用margin-right: 0;右对齐第二个元素从主div中删除justify-contect: center

&#13;
&#13;
.flexbox { 
    display: flex; 
    height: 200px;
    background: yellow;
}
.box1 { 
  width: 100px; 
  margin-left: 50%;
  background: blue;
}
.box2 { 
    width: 100px; 
    margin-left: auto;
    margin-right: 0;
    background: green;
}
&#13;
<div class="flexbox">
    <div class="box1">fdgdfg</div>
    <div class="box2">dfgdg</div>
</div>
&#13;
&#13;
&#13;