0

I have a very specific and annoying use case which needs to be implemented.

Basically on my screen I am supposed to have multiple items with a fixed width across the screen. Ideally these items must look nicely centered when the row is full, but if it is not full they need to be aligned to the left, which removed the ability to simply do justify-content: center and be done with it.

So... it probably is a case in which I need a fixed margin on the left and right to make a full column look centered, but the question becomes how can I make it have that centered look in various different screen sizes?

Keep in mind that I am free to use the styles using JS if something more dynamic is needed.

Here is a sample app with the two different scenarios which hopefully will help illustrate the problem:

const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
const App = () => {

  return (
  <div>
    <div className='container1'>
      <h3>Case 1 - justify-content: center</h3>
      <p>When the row is filled this is good, but see the second row? I need that to be aligned with the first row to the left</p>
      {items.map(i => <div key={`container1-${i}`} className='item' style={{ backgroundColor: 'blue'}}/> )}
    </div>
    
    <div className='container2'>
      <h3>Case 2 - justify-content: flex-start</h3>
      <p>Here obviously the items do not look centered. Of course I can add some margin to the left to give it that look, but
      how  could I make it look like a full row is centered?
      </p>
      <p>The fact that the full line and the emptier line are aligned to the left is what I want, but when the line is full it needs to look like it is centered.</p>
      {items.map(i => <div key={`container2-${i}`} className='item' style={{ backgroundColor: 'red'}}/>)}
    </div>

  </div>
  )
}


ReactDOM.render(
    <App />,
    document.getElementById('app')
);
.item {
  min-width: 50px;
  width: 50px;
  height: 50px;
  margin: 1px;
}

.container1 {
  border: 1px solid blue;
  width: 60%;
  margin: 10px;
  padding: 5px;
  
  display: flex;
  flex-direction: row;
  justify-content: center;
  flex-wrap: wrap;
}

.container2 {
  border: 1px solid red;
  width: 60%;
  margin: 10px;
  padding: 5px;
  
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  flex-wrap: wrap;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="app"></div>
theJuls
  • 5,731
  • 10
  • 56
  • 121
  • check this: https://stackoverflow.com/a/65395384/8620333 a solution to your specific case but you check also the other duplicate and you will find more generic one – Temani Afif Aug 31 '21 at 20:04

0 Answers0