CyberJ
CyberJ

Reputation: 1124

Flex move same width elements to next line

I'm trying to achieve the following with CSS3 flex:

enter image description here

All the blocks are 33% width and 3 per row. I don't have div for rows, just blocks and the ones that don't fit should move below.

<div class="wrap">
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
</div>

My CSS:

.wrap {
  display: flex;
  flex: 1;
}

.block {
  display: flex;
  flex-direction: column;
  flex: 1 0 33%;
  width: 33%;
}

Any block after the third moves to the bottom which is what I want but it stretches at 100% instead of retaining its 30% width. If there are two blocks on the second row, they stretch 50% each...

How can I make them all stay at 33%?

Note: the html is dynamic and must remain the same. I can't wrap every 3 blocks in a row div.

Upvotes: 0

Views: 1493

Answers (2)

Brian H.
Brian H.

Reputation: 844

There are a few things you need to change and a few other unnecesary ones, however since i don't know what the complete template will look like, i'll mark those in comments.

.wrap {
  display: flex;
  flex: 1; /* unnecesary */
  flex-wrap: wrap;

  /* the following styles are just so the result is visible */
  background-color: blue;
}

.block {
  display: flex; /* unnecesary, only the container needs to be flex */
                 /* unless this is another flex container */
  flex-direction: column; /* also unnecesary unless it's for purposes not shown in the example */
  width: 33.3333%;

  /* the following styles are just so the result is visible */
  height: 20px;
  background-color: red;
}
<div class="wrap">
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
</div>

Upvotes: 1

sara moghanam
sara moghanam

Reputation: 125

Use the Flex-basis property as following

.wrap {
  display: flex;
  flex-flow: wrap;
}
.wrap .block{
  flex-basis: 33.33%
}
<div class="wrap">
      <div class="block">text</div>
      <div class="block">text</div>
      <div class="block">text</div>
      <div class="block">text</div>
      <div class="block">text</div>
 </div>

Upvotes: 1

Related Questions