Css moves an element to a new column if height is reached

I have a list from which I would like to build two columns. The list may contain a variable number of elements, but max. out of 8

I always want 4 elements in the first column. I already tried column-count: 2, but this does not work fine on an unequal number, because the first line should contain 4 elements.

.container {
  border: 1px solid red;
  width: 300px;
  height: 90px;
}
<div class="container">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
  </ul>
</div>
Run codeHide result
+4
source share
2 answers

You can do this using display:flex:

ul {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  width: 300px;
  height: 200px;
}
li {
  height: 25%;
}
<div class="container">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
  </ul>
</div>
Run codeHide result
+9
source

Try to fulfill this requirement.

<!DOCTYPE html>
<html lang="en-US">

<head>
    <style>
        .container ul li {
            list-style-type: none;
            width: 500px;
        }
        
        .container ul li:nth-child(4n+1) {
            border-top: 1px solid red;
            border-left: 1px solid red;
            border-right: 1px solid red;
        }
        
        .container ul li:nth-child(4n+2), .container ul li:nth-child(4n+3) {
            border-left: 1px solid red;
            border-right: 1px solid red;
        }
        
        .container ul li:nth-child(4n+4){
            border-bottom: 1px solid red;
            border-left: 1px solid red;
            border-right: 1px solid red;
            margin-bottom: 5px;
        }
        
        .container ul li:last-child {
            border-bottom: 1px solid red;
        }
    </style>
</head>

<body>
    <div class="container">
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
        </ul>
    </div>
</body>

</html>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1668400/


All Articles