0

How do I align my items to always place it on top. I am using flex to my container.

Note: The number of items are dynamically generated.

enter image description here

<div class="container">
  <div class="item">ITEM 1</div>
  <div class="item second">ITEM 2</div>
  <div class="item">ITEM 3</div>
</div>

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

 .item {
     width: 45%;
     height: 100px;
     background-color: lightgray;
     margin: 0 20px 20px 0;
     display: flex;
     justify-content: center;
     align-items: center;
 }

 .second {
     height: 150px;
 }

Here is my plunkr

kmhigashioka
  • 521
  • 5
  • 14
  • As far as I know this won't be possible with flexbox since flexbox is only for aligning the items in one direction (horizontal or vertical). You can change the direction to flex-flow: column but then you would have "ITEM 2" below "ITEM 1". To achieve your desired output you would have to use grid layout (display: grid) – cloned Mar 19 '19 at 08:00
  • Can you provide some example? – kmhigashioka Mar 19 '19 at 08:59

1 Answers1

1

the easiest way is that put item-1 and item-3 (elements on same column) on one div and then apply property to that div tag.I added the snippet below.

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

.item {
  width: 100%;
  height: 100px;
  background-color: lightgray;
  margin: 0 20px 20px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.second {
  height: 150px;
}

.column{
  width:45%;
}
.clm-1{
  margin: 0 20px 20px 0;
}
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <div class="container">
    <div class="column clm-1">
      <div class="item">ITEM 1</div>
      <div class="item">ITEM 3</div>
     </div>
     <div class="column clm-2">
      <div class="item second">ITEM 2</div>
     </div>
    </div>
  </body>

</html>
ADH - THE TECHIE GUY
  • 4,125
  • 3
  • 31
  • 54
  • Sorry, I forgot to mention that the number of items are dynamically generated. – kmhigashioka Mar 19 '19 at 08:58
  • sure but if the iteration loop are odd you can put your div on the left column else on the right – Sfili_81 Mar 19 '19 at 09:04
  • @Sfili_81 That won't work, as if a user resize their device (e.g. flip a tablet), the content will dynamically change its element's size. – Asons Mar 19 '19 at 09:11