Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating three columns flexbox

I have a component in react which i, iterating in a loop. This component will always be shown three times and I want them to show in one single row (each component a column). The examples I have seen manually adds "flex:1;" and so on for every column, but since im iterating its not possible.

It looks like this:

<div className="styles.grid">
  <!-- stuff  -->
</div>

Above is going to be shown three times, and want them all in one single row (each going to be a column).

I have tried:

.grid {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
} 

Does not work. Any help?

like image 433
Arte2 Avatar asked Mar 18 '26 18:03

Arte2


2 Answers

You can remove the flex-wrap to let all the flex items be on the same row, and give each flex item a third of the width.

Example

function App() {
  return (
    <div className="grid">
      <div className="grid-item item-1">Foo</div>
      <div className="grid-item item-2">Bar</div>
      <div className="grid-item item-3">Baz</div>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));
.grid {
  display: flex;
}

.grid-item {
  width: 33.33333%;
  height: 200px;
}
.item-1 {
  background-color: red;
}
.item-2 {
  background-color: green;
}
.item-3 {
  background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>
like image 136
Tholle Avatar answered Mar 20 '26 08:03

Tholle


Try using flex-grow: 1 on the children columns. This tells the children to grow equally to fill their parents width.

For more info on flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Below is a simple 3 column example, where each column expands equally.

.parent {
  width: 100%;
  height: 200px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.col {
   flex-grow: 1;
   height: 200px;
   border: 1px solid black;
}
<div class="parent">
  <div class="col">1</div>
  <div class="col">2</div>
  <div class="col">3</div>
</div>
like image 39
Matthew Varga Avatar answered Mar 20 '26 07:03

Matthew Varga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!