2

I want to add the items in the container from top to bottom and left to right to display items in several columns. Here is the code what I'm working on.

#container {
  display: inline-flex;
  flex-direction: column;
  flex-wrap: wrap;
  max-height: 250px;
  padding: 10px;
  margin: 20px;
  background-color: blue;
}
#container .item {
  width: 80px;
  height: 50px;
  background-color: red;
  margin: 10px;
}
<div id="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
</div>

<div id="container">
  <div class="item">1</div>
</div>

When I set the display property as inline-flex the container does include only a single column, but not all the columns. If I set the display property as flex, the container width is larger than the total width of all the columns.

Here is the image what I need for better understanding. List items from top to bottom and left to right

How can I make container width the same with the content width?

Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
lyraid
  • 43
  • 5

1 Answers1

1

Here’s a solution using Grid Layout via display: inline-grid.

grid-template-rows: repeat(3, max-content) means there should be three rows, each max-content high. I used max-content instead of 1fr because when I tried using 1fr, the second container had empty space at the bottom, making the container three rows tall. max-content seems to fix this by collapsing those rows when there is no item inside them.

#container {
  display: inline-grid;
  grid-template-rows: repeat(3, max-content);
  grid-auto-flow: column;
  
  padding: 10px;
  margin: 20px;
  background-color: blue;
}
#container .item {
  width: 80px;
  height: 50px;
  background-color: red;
  margin: 10px;
}
<div id="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
</div>

<div id="container">
  <div class="item">1</div>
</div>

Also, if the margin: 10px you added to #container .item was just for adding margin between the Flex items, you can now replace it with gap: 10px in #container.

Finally, the inline in display: inline-grid may cause you trouble due to the whitespace between elements being rendered as text. If this causes trouble you should be able to use display: grid instead, then wrap both containers in another div with display: flex.

Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131