'Is this possible to do with a Flexbox?
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 class="holder">
<div class="section-one"></div>
<div class="section-two"></div>
<div class="section-three"></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.
Solution 1:[1]
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 class="holder">
<div class="section-one">1</div>
<div class="section-two">2</div>
<div class="section-three">3</div>
</div>
Solution 2:[2]
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 class="holder">
<div class="column left-column">
<div class="column-header">First Column</div>
<div class="section-one">section 1</div>
</div>
<div class="column right-column">
<div class="column-header">Second Column</div>
<div class="section-two">Section 2</div>
<div class="section-three">section 3</div>
</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gavgrif |
| Solution 2 |
