Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS grid: how to bring elements in same grid area to line up?

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?

like image 785
Boldewyn Avatar asked Mar 09 '17 07:03

Boldewyn


People also ask

How do you align items in CSS Grid?

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 .

How can I align the content inside of the grid cells?

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.


1 Answers

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>
like image 115
beerwin Avatar answered Oct 11 '22 04:10

beerwin