Home > Net >  Create unknown amount of columns
Create unknown amount of columns

Time:09-07

Lets say I have some list items:

<ul>
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
   <li>Item 5</li>
   <li>Item 6</li>
   <li>Item 7</li>
</ul>

By default, they are just below each other like this:

  • Item 1
  • Item 2
  • Item 3
  • Item 4
  • Item 5
  • Item 6
  • Item 7

But what can I do if I want the ul to have a fixed height, and the items inside should flow in columns like on this picture:

enter image description here

The width of the different items should be flexible, so if an item gets bigger, the column should also get bigger:

enter image description here

It seems like a simple use case - but I tried with floats, flex (with wrap), but I cant find any really working solution.

Any ideas?

CodePudding user response:

Try this:

  ul { 
    list-style-type: none;
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    height: 80vh;
  }

  ul li { 
    padding: 10px;
    background-color: lavender;
    border: solid 1px black;
    margin: 5px;
    width: fit-content;
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>  
  <ul>
   <li>Item 1</li>
   <li>Item 2aaaaaaaaaaaaaaa</li>
   <li>Item 3</li>
   <li>Item 4</li>
   <li>Item 5</li>
   <li>Item 6</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
   <li>Item 7</li>
  </ul>
</body>
</html>

CodePudding user response:

I figured it out. The key is "align-content" of flexbox. This property is doing exactly what I want.

Here is my pen: https://codepen.io/web265p3/pen/KKRdXBg

<ul>
  <li>Item 1</li>
  <li>Item 1</li>
  <li>Item 1xxxx</li>
  <li>Item 1</li>
  <li>Item 1</li>
  <li>Item 1</li>
  <li>Item 1</li>
</ul>

ul {
    list-style-type: none;
    display: flex;
    flex-direction: column;
    align-content: flex-start;
    flex-wrap: wrap;
    height: 200px;
}
ul li {
    padding: 10px;
    background-color: lavender;
    border: solid 1px black;
    margin: 5px;
    width: fit-content;
}
  •  Tags:  
  • css
  • Related