1

Edit 983oq88yro

import React from 'react';
import { render } from 'react-dom';

const styles = {
  display: 'flex',
  justifyContent: 'center',
  flexWrap: 'wrap',
};

const item = {
  width: '26%',
}

const container = {
   marginLeft: 'auto',  
   marginRight: 'auto',
   width: '100%',
}

const App = () => (
  <div style={container}>
    <div style={styles}>
      <div style={item}>test1</div>
      <div style={item}>test2</div>
      <div style={item}>test3</div>
      <div style={item}>test4</div>
    </div>
  </div>
);

render(<App />, document.getElementById('root'));

Is there a way to make test4 appear under test1, but still keep the items centralised to the parent container?

Changing justifyContent to flex-start would cause the entire flexbox to align to the left of the parent.

Avery235
  • 4,756
  • 12
  • 49
  • 83
  • In the dupe link, [this answer](https://stackoverflow.com/a/46088753/2827823) show how to left align items and keep the parent centered using Flexbox. – Asons Nov 10 '17 at 12:11

2 Answers2

0
  1. your items should have flex: 1 1 33% as a rule, this is a shortcut for flex-grow, flex-shrink and flex-basis;
  2. you have to select the fourth item and set flex-basis: 100%;
  3. create children inside the flexbox items and then centralise them.

In my experience you should never have a component as a direct children of a flexbox; you should always use the items as containers for your components.

Keep in mind that flexbox is not well supported by old browsers (IE10) and most of IE versions have problem with flexbox. Use it carefully.

Michael Mammoliti
  • 1,517
  • 13
  • 11
  • the actual use case has a fixed width rather than percentage, so i'd have to detect the window width, calculate the paddings etc to get the number of elements in last row. – Avery235 Nov 05 '17 at 20:18
  • Not sure what are you trying to achieve, would be nice having an example. The container of the flexbox could be fixed and flex items could be fixed as well if needed. Anyway flexbox should be always 100%, then it's the parent which decides the width of it's children (in this case the flexbox container would be the children of a general container). – Michael Mammoliti Nov 05 '17 at 20:54
0

You need to specify width on the inner container and add margin: 0 auto to center it.

Something like that

const styles = {
  display: 'flex',
  width: '70%',
  flexWrap: 'wrap',
  marginLeft: 'auto',
  marginRight: 'auto',
};

Edit qk1wprnxxw

felixmosh
  • 32,615
  • 9
  • 69
  • 88