My target is to use CSS grid layout for a two-column masonry layout of boxes. Given an element with children:
<section>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</section>
bring the children to sort themselves alternately into columns. My idea was to have two grid areas left
and right
and telling the children to split into them:
section {
display: grid;
grid-template-areas: "left right";
}
div:nth-child(odd) {
grid-area: left;
}
div:nth-child(even) {
grid-area: right;
}
Here's a JSBin that illustrates my current state: https://jsbin.com/zaduruv/edit?html,css,output
Unfortunately, the elements react quite identical to as if they had position:absolute
set. That is, they all crowd towards the top and overlap one another.
Is there any possibility with the CSS grid layout properties to bring the children to line up in the columns, like they'd do normally with position: static
?
To align the item horizontally within the grid, we use the justify-content property and set it to center . With justify-content we can align the columns start , end , stretch or center .
To center content horizontally in a grid item, you can use the text-align property. Note that for vertical centering, vertical-align: middle will not work. This is because the vertical-align property applies only to inline and table-cell containers.
You can't. Since elements can overlap each other in a CSS grid, it doesn't even try to align them. As its name suggests, it is a grid, not a column layout.
A better solution would be to use CSS multi-column layout, as the snippet below.
The only problem with the multi-column layout is, that it distributes the divs vertically instead of horizontally, so you get this:
1 4 2 5 3 6
instead of this:
1 2 3 4 5 6
section {
-webkit-column-count: 2; /* Chrome, Safari, Opera */
-moz-column-count: 2; /* Firefox */
column-count: 2;
-webkit-column-gap: 0;
-moz-column-gap: 0;
column-gap: 0;
width: 500px;
background-color: #e0e0e0;
}
div {
width: 250px;
display: inline-block;
}
div:nth-child(1) {
background-color: #c1c0c1;
height: 100px;
}
div:nth-child(2) {
background-color: #fedbc1;
height: 50px;
}
div:nth-child(3) {
background-color: #dec34a;
height: 130px;
}
div:nth-child(4) {
background-color: #ce3294;
height: 110px;
}
div:nth-child(5) {
background-color: #99deac;
height: 80px;
}
div:nth-child(6) {
background-color: #aade34;
height: 190px;
}
<section>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</section>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With