Jaeeun Lee
Jaeeun Lee

Reputation: 3196

Flexbox multiple coumns

I need to display a questionnaire with multiple sets of options. When there are only two options, they should be displayed in two columns that have 50% width each. When there are more than two, they should be displayed in three columns that have 33.3333% with each. Currently I'm having a difficulty making the columns to 50% width when there are only two of them.

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%;
    }
  }
}   

Upvotes: 0

Views: 61

Answers (1)

Asons
Asons

Reputation: 87303

Assuming they should wrap when more than 3 items, here is a pretty cool trick using the nth-child selector and target the items based on how many there are.

Their width is set to a default of 33.333% and then when there is only 2 items, the .answers .answer:first-child:nth-last-child(2) kicks in and make them 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>

Upvotes: 1

Related Questions