Stephen
Stephen

Reputation: 1183

CSS Flexbox style changes based on amount of elements

I am trying to learn Flexbox and I am having a problem with this exercise. The task is to have a div with 2 to 4 div's inside of it. When there are 2 or 3 div's they should be divided equal width and all should be the height of the main div. But when there are 4 div elements inside the main div, then they would be in two rows which contain two div's each.

How can I make this possible? I have tried some on my own but I couldn't get it to work:

<div id="wrapper">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

This is the CSS I have created:

#wrapper{
  width: 100%;
  height: 100%;

  display: flex;
  flex-wrap: wrap;
}

.item{
  min-width: 33%;
}

Picture of how it should look with 2 elements inside the wrapper Div

3 elements in the main Div

Picture of how it should look with 3 elements inside the wrapper Div

3 elements in the main Div

Picture of how it should look with 4 elements inside the wrapper Div

4 elements in the main Div

Upvotes: 2

Views: 475

Answers (2)

Temani Afif
Temani Afif

Reputation: 273100

Consider nth-child to control this:

#wrapper {
  height: 100vh;
  display: flex;
  flex-wrap: wrap;
  border:5px solid white;
  box-sizing:border-box;
}


.item {
  flex-grow:1;
}

/* apply when there is 4 items */
#wrapper > :first-child:nth-last-child(4),
#wrapper > :first-child:nth-last-child(4) ~ *{
  flex-basis:50%;
}

body {
  margin:auto;
}
<div id="wrapper">
  <div class="item" style="background:red;"></div>
  <div class="item" style="background:blue;"></div>
</div>
<div id="wrapper">
  <div class="item" style="background:red;"></div>
  <div class="item" style="background:blue;"></div>
  <div class="item" style="background:green;"></div>
</div>
<div id="wrapper">
  <div class="item" style="background:red;"></div>
  <div class="item" style="background:blue;"></div>
  <div class="item" style="background:green;"></div>
  <div class="item" style="background:yellow;"></div>
</div>

Upvotes: 3

possum
possum

Reputation: 2927

Try changing the following to your CSS

.item{
  min-width: 33%;
  flex-grow: 1;
}

.item:first-child:nth-last-child(4),
.item:first-child:nth-last-child(4) ~ .item {
    min-width: 50%;
}

This only works for CSS3. You could imagine scaling it for more items with additional entries

Upvotes: 2

Related Questions