Home > Software engineering >  Is this possible to do with a Flexbox?
Is this possible to do with a Flexbox?

Time:03-20

I have three divs inside of a flexbox and I want to get them aligned in a certain way. Here is the way the HTML is set up.

 <div >
    <div ></div>
    <div ></div>
    <div ></div>
 </div>

I need the items to lay out like this:

first column second column
section one section two
section one section three

I do not actually want them in a table. I need two columns where each item has a width of 50%, but the second and third section are stacked on top of each other. I know one solution is to have two columns, but for reasons I cannot say I cannot do that. I need to have three items that are all in the same row.

CodePudding user response:

Although I would agree that CSS-grid is a good choice for this - its not hard to do with flexbox.

Simply create two divs aligned horizontally (flex defaults to flex-direction:row - so you don't need to specify this) in order to create left and right columns and put the first section div in the left column - then the other two section divs in the right column and use flex-direction:column to get the vertical alignment.

.holder {
   display: flex;
   width: 400px
}

.column {
 flex-grow: 1;
 flex-basis: 50%;
 border: solid 1px #a9a9a9;
 display: flex;
 flex-direction: column
}

 .column-header {
background: #d4d4d4;
border-bottom: solid 1px #a9a9a9;
 padding: 8px 16px;

}

.column div:not(.column-header) {
 padding: 8px 16px;
 height: 100%
}

.section-one {
  background: lime
}

.section-two {
  background: aqua;
}

.section-three {
  background: yellow;
}
<div >
  <div >
    <div >First Column</div>
    <div >section 1</div>
  </div>
  <div >
    <div >Second Column</div>
    <div >Section 2</div>
    <div >section 3</div>
  </div>
 </div>

CodePudding user response:

The easiest solution with your markup would be to use CSS-Grid. Simply create a 2 column grid and let the first element span 2 rows with grid-row: span 2

.holder {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.section-one {
  grid-row: span 2;
}


/* For demo purpose only */
div > div {
  min-height: 50px;
  box-shadow: 0 0 0 2px red;
  display: flex;
  justify-content: center;
  align-items: center;
}

.holder {
  gap: 2px;
}
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
</div>

  • Related