Flexible rack layout

I need to create a layout that will contain a list of elements in two columns. As I showed below:

.container { border: 1px solid red; height: 300px; display: flex; flex-direction: column; justify-content: flex-start; flex-wrap: wrap; } .item { border: 1px dashed blue; height: 50px; } 
 <div class="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 class="item">6</div> <div class="item">7</div> <div class="item">8</div> </div> 
But there is a problem with such a layout. If there is only 1 element, it will have a full width. And I need to keep the columns even if there are several elements.
+5
source share
1 answer

You can set the maximum width for an element to 50%. This will maintain almost the same width, no matter what. I say almost because your borders are also set.

For the width to be the same, you also need to set the window size: border-box for the element.

So your code will be:

 .item { border: 1px dashed blue; height: 50px; box-sizing: border-box; max-width: 50%; } 

 .container { border: 1px solid red; height: 300px; display: flex; flex-direction: column; justify-content: flex-start; flex-wrap: wrap; } .item { border: 1px dashed blue; height: 50px; box-sizing: border-box; max-width: 50%; } 
 <div class="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 class="item">6</div> <div class="item">7</div> <div class="item">8</div> </div> 
+5
source

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


All Articles