如果只有一列,Flexbox会将列对齐到右侧

时间:2017-07-27 11:23:50

标签: css flexbox

我有两列flexbox布局。但是,有时只有一列,在这种情况下,列应该向右对齐。目前,该列与左侧对齐。

https://codepen.io/sleepydada/pen/rzVRxL

HTML:

<div class="answers">
  <div class="answer">first answer</div>
  <div class="answer">second answer</div>
</div>
<div class="answers">
  <div class="answer">first answer</div>
</div>

SCSS:

* {
  box-sizing: border-box;
}

.answers {
  border: 2px solid black;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  &:first-of-type {
    background: #ccc;
  }

  .answer {
    background: crimson;
    margin: 20px 0;
    border: 1px solid blue;
    flex: 0 0 33.3333%;
  }
}   

2 个答案:

答案 0 :(得分:2)

您可以添加此CSS:

.answer:only-of-type {
  margin-left: auto;
}

来自MDN

  

:only-of-type CSS伪类表示没有的元素   同类型的兄弟姐妹。

codepen

&#13;
&#13;
* {
  box-sizing: border-box;
}

.answers {
  border: 2px solid black;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.answers:first-of-type {
  background: #ccc;
}

.answers .answer {
  background: crimson;
  margin: 20px 0;
  border: 1px solid blue;
  flex: 0 0 33.3333%;
}

.answers .answer:only-of-type {
  margin-left: auto;
}
&#13;
<div class="answers">
  <div class="answer">first answer</div>
  <div class="answer">second answer</div>
</div>
<div class="answers">
  <div class="answer">first answer</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以添加一个height设置为0

的不可见div

* {
  box-sizing: border-box;
}

.invisible {
  height: 0;
  border: none !important;
}

.answers {
  border: 2px solid black;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.answers:first-of-type {
  background: #ccc;
}
.answers .answer {
  background: crimson;
  margin: 20px 0;
  border: 1px solid blue;
  flex: 0 0 33.3333%;
}
<div class="answers">
  <div class="answer">first answer</div>
  <div class="answer invisible"><!--invisible div--></div>
  <div class="answer">second answer</div>
</div>
<div class="answers">
  <div class="answer invisible"><!--invisible div--></div>
  <div class="answer">first answer</div>
</div>