Vololodymyr
Vololodymyr

Reputation: 2288

Two columns flex-box layout

I need create layout which will contain list of items in two columns. Like 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 layout. If there will be only 1 item - it will take full width. And i need to keep columns even if there are a few items.

Upvotes: 31

Views: 111892

Answers (3)

Milan Chandro
Milan Chandro

Reputation: 2493

I prefer to use the following code below:

.container {
  display: flex;
  flex-wrap: wrap;
}

.item {
  flex-basis: 50%;
  box-sizing: border-box;
}

Upvotes: 12

farid teymouri
farid teymouri

Reputation: 191

If you want to create fixed two columns without changing on dependencies (like device responsive), you don't need to use Flex

try this one on child element's

.childs {
display: inline-block;
max-width:50%;
width: 100%;
}

Upvotes: 0

Chris Elioglou
Chris Elioglou

Reputation: 649

You can set a max-width for the item, equal to 50%. This will keep it, almost, the same width no matter what. I say almost because you also have borders set.

In order to keep the width exactly the same, you also have to set box-sizing: border-box for item.

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>

Upvotes: 40

Related Questions