3

I have a practice app that dynamically populates content into 4 column container.

I'm trying to space the contents in the container evenly, using flexbox.

It looks great when there are 4 items in a row, but when there are less, the items are really spaced apart because they're not aligned left.

I could space out the containers using flexbox plus margins on each item, but then the items are also pushed apart from the border, which I'm trying to avoid.

Hope that makes sense. Below is a recreation of what I'm trying to achieve. Appreciate any input I could get :)

html {
  border: 1px solid black;
  margin: 0 auto;
  width: 800px;
}

body {
  margin: 0;
}

ul {
  box-sizing: border-box;
  display: flex;
  flex-wrap:wrap;
  justify-content: space-between;
  padding: 0;
}

li {
  border: 1px solid black;
  box-sizing: border-box;
  list-style-type: none;
  text-align: center;
  width: 180px;
  /* margin: 1%; MUST comment out justify content when using this, to get an idea what I'm trying to achieve. Using margin pushes out the left-hand items, which I'm trying to avoid.*/
}
<div class="container">
  <nav>
    <a>Link 1</a>
    <a>Link 2</a>    
  </nav>

  <div class="content">
    <ul>
      <li><p>1</p></li>
      <li><p>2</p></li>
      <li><p>3</p></li>
      <li><p>4</p></li>
      <li><p>5</p></li>
      <li><p>6</p></li>      
      <li><p>7</p></li>      
    </ul>
  </div>
</div>
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
  • make `li {... flex-basis: 180px; flex-grow: 1...}` instead of `width`. This will alow the `
  • ` to grow/shrink to fill the line, but wraps when there is less than 180px space left. Also: don't style `` it is mean to be a parent container for your document, holding all kinds of defaults, etc. Style `` instead.
  • – Rene van der Lende Jul 17 '20 at 15:31
  • Thank you for the response, much appreciated. This looks great, but I'd like for them to have the same width and spaced out evenly, while also aligned left. If I apply `flex-grow`, the items stretch. –  Jul 17 '20 at 15:35
  • This StackOverflow question seems relevant: https://stackoverflow.com/questions/18744164/flex-box-align-last-row-to-grid. – Jacob Lockard Jul 17 '20 at 15:36
  • Thank you, reading up on it. Seems like the trick is to add an empty div at the end of the list. Tried one of the solutions, and though seems promising, it broke the layout of the last row (but only the last row). Will keep reading, thanks. –  Jul 17 '20 at 15:50
  • Not sure if it would help, perhaps can try using ul's ```justifycontent: start``` and use the ```li's margin: 1%``` instead. Then add in a css class ```li:nth-child(5n), li:first-child: margin-left: 0px``` to take away the left margin of the first element of each row. – Jones Lee Jul 18 '20 at 09:30
  • Duplicate: https://stackoverflow.com/questions/18744164/flex-box-align-last-row-to-grid?rq=1 – Peter Højlund Palluth Dec 05 '22 at 13:13