CSS Flex - Space Between but align elements left?

Viewed 2093

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>

1 Answers

enter image description hereBased on your question you can use the below code, so that all item align to the left and always 4 items will be in a row.

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: start;
  padding: 1%;
}

li {
  border: 1px solid black;
  box-sizing: border-box;
  list-style-type: none;
  text-align: center;
  flex-basis: 23%;
  margin: 1%;
}
<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>

UPDATE

I have changed the answer based on your comment to get 1% margin, so that all items will have equal space between them.

Related