Flexbox多个coumns

时间:2017-07-26 16:08:02

标签: html css css3 sass flexbox

我需要显示一组包含多组选项的调查问卷。当只有两个选项时,它们应显示在两列中,每列宽度为50%。当有两个以上时,它们应显示在三列中,每列各有33.3333%。目前,当只有两个列时,我很难将列的宽度设置为50%。

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

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 class="answer">second answer</div>
  <div class="answer">third answer</div>
  <div class="answer">four answer</div>
</div>

SCSS:

* {
  box-sizing: border-box;
}

.answers {
  border: 2px solid black;
  margin-bottom: 20px;

   @media (min-width: 480px) {
     display: flex;
     flex-wrap: wrap;
     justify-content: center;
  }

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

  .answer {
    width: 100%;
    background: crimson;
    margin: 20px 0;
    border: 1px solid blue;

    @media (min-width: 480px) {
      flex: 0 0 33.3333%;
    }
  }
}   

1 个答案:

答案 0 :(得分:2)

假设他们应该在超过3个项目时进行换行,这里使用nth-child选择器是一个非常酷的技巧,并根据有多少项来定位项目。

他们的宽度设置为默认值33.333%,然后当只有2个项目时,.answers .answer:first-child:nth-last-child(2)启动并使其成为50%

* {
  box-sizing: border-box;
}

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

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

.answers .answer {
  background: crimson;
  margin: 20px 0;
  border: 1px solid blue;
  flex-basis: 33.333%;                         /*  default width is 33%  */
}

.answers .answer:first-child:nth-last-child(2),
.answers .answer:first-child:nth-last-child(2) ~ .answer {  /*  2 items  */
  flex-basis: 50%;
}
<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 class="answer">second answer</div>
  <div class="answer">third answer</div>
  <div class="answer">four answer</div>
</div>