Home  >  Q&A  >  body text

Use shrink wrap flex boxes to wrap flex items so they can be centered

I have a flexbox with packed content. How to shrink a flexbox to its content? The fundamental problem I'm trying to solve is centering the flexbox. This image describes my problem:

How can I achieve this goal? Can this be achieved with pure CSS? I don't know in advance whether Flexbox will wrap to 1, 2 or 3 columns. The width of the element is known. The height would preferably be unknown, but I could decide on a constant height if that was easier.

is neither width:min-content, width:max-content, width:fit-content nor inline-flex< /code> seems to solve the problem.

JS Fiddle: https://jsfiddle.net/oznts5bv/

.container {
  display:flex;
  flex-wrap:wrap;
  border:1px dashed magenta;
}

.container div {
  width:100px;
  height:60px;
  border:1px solid black;
}
<div class="container">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>

P粉807239416P粉807239416402 days ago526

reply all(1)I'll reply

  • P粉070918777

    P粉0709187772023-09-14 14:26:32

    Two examples were created: using display: flex; and display: grid;. The second option may suit you better:

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      display: flex;
      flex-direction: column;
      align-items: center;
      overflow-y: scroll;
    }
    
    .container {
      display: flex;
      flex-wrap: wrap;
      border: 1px dashed magenta;
      max-width: min(100%, 302px);
    }
    
    .container div {
      width: 100px;
      height: 60px;
      border: 1px solid black;
    }
    
    .grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    }
    <input type="range" min="100" max="600" value="302" oninput="document.querySelectorAll('.container').forEach(el => el.style.maxWidth = 'min(100%, ' + this.value + 'px)')">
    <div class="container">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
    </div>
    <br>
    <div class="container grid">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
    </div>

    reply
    0
  • Cancelreply