I would like to wrap each element without leaving any space left from a previous div
. Each div
has a variable height and I would like the elements to stack on top of each other.
<div className="Notes-Grid" id='Notes-Grid'>
<Note data={ "Create a new Post"} />
<Note data={ "Oh acceptance apartments up sympathize astonished delightful.
Waiting him new lasting towards. Continuing melancholy especially so to.
Me unpleasing impossible in attachment announcing so astonished. What ask leaf may
nor upon door. Tended remain my do stairs. Oh smiling amiable am so visited cordial in offices hearted."} />
<Note data={ "Test"} />
<Note data={ "Testing 1233"} />
<Note data={ "Test"} />
<Note data={
"Oh acceptance apartments up sympathize astonished delightful. Waiting him new lasting towards. Continuing melancholy especially so to. Me unpleasing impossible in attachment announcing so astonished. What ask leaf may nor upon door. Tended remain my do stairs. Oh smiling amiable am so visited cordial in offices hearted."} />
</div>
.Notes-Grid {
display: flex;
flex-direction: row;
justify-content: flex-start;
flex-wrap: wrap;
}
.Note {
background-color: var(--dark_gray);
flex: 0 0 300px;
height: fit-content;
border: 4px solid red;
}
Output:
What I am trying to recreate:
If this can’t be done using flexbox
I am open to alternatives.
2
Answers
Use masonry (https://masonry.desandro.com/) for this layout. If it needs to be done through css only use columns.
There are essentially two ways to go about this:
.Notes-Grid
box: Place each div in the columns right after the other, and let them just take the space they need.Notes-Grid
box: Make all three columns the same height, and let the divs inside grow – this will result in some divs taking in more space than they would needThere really is no other way around: Either have straight line, but the cells are growing, or have non-straight line, with original size of the cells being maintained.
Implementation
For both options, you need
.Note-Column
divs for each column (in this case 3). They need to be siblings to each other and contain the given grid cell divs, which we will give a classname of.Note-Cell
. Then, let.Notes-Grid
bedisplay: flex
, andflex-direction: row
. The.Note-Column
‘s needflex: 1 1 0
now, so that they grow and shrink accordingly.With this, you will have equal width columns, and the cells in the columns should be placed one after the other. Option #1 should be implemented by now.
For Option #2, you simply also set
display: flex
on the.Note-Column
‘s, and give.Note-Cell
‘sflex: 1 1 0
. Also include ajustify-content: space-between
on the.Note-Column
‘s, in order to place the first and last cell on the border of.Note-Grid
, which will achieve the mentioned straight bottom edge.Voilá, now your Note-Grid should be working like you expect.
Flexboxes
If you are confused by the flex commands used, take a look at this guide. I think flexboxes are explained quite well there.