Two-Column Newspaper Layout with CSS Grid

988 views Asked by At

I've got CSS grid to produce a two-column layout. But the problem is that it's not top-aligning content in each column.

For example, in the second column, the last element should top-align to but up against the other column-two element.

body>div {
  display: grid;
  grid-template-columns: 50% 50%;
  grid-template-rows: auto auto;
  grid-auto-flow: column;
  /* https://codepen.io/maddesigns/pen/oZGWRN */
  /* https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow */
}

body>div>div:nth-of-type(1) {
  height: 300px;
}

body>div>div:nth-of-type(2) {
  height: 100px;
}

body>div>div:nth-of-type(3) {
  height: 200px;
}
<div style="">
  <div style="background:red">
    1
  </div>
  <div style="background:green;">
    2
  </div>
  <div style="background:yellow">
    3
  </div>
  <div style="background:pink">
    4
  </div>
</div>

I couldn't use flex for this layout because I wanted to achieve this layout without defining the container height. column-count:2 would have worked without defining the container height but then I couldn't use div reordering.

So I'm using CSS grid because div reordering is still available (e.g./i.e. order:–1; works well) and it auto-divies up what to put in each of the two columns.

2

There are 2 answers

1
John On

The gird is acting exactly as intended, to keep order and symmetry just like this. I can recommend using 2 grids side by side to achieve what you're looking for. Here's an example that I made to demonstrate this:

.left{
  display: grid;
  grid-template-rows: auto auto;
  grid-auto-flow: column;
  width: 50%;
  float: left;
  /* https://codepen.io/maddesigns/pen/oZGWRN */
  /* https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow */
}

.right{
  display: grid;
  grid-template-rows: auto auto;
  grid-auto-flow: column;
   width: 50%;
  /* https://codepen.io/maddesigns/pen/oZGWRN */
  /* https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow */
}

.left>div:nth-of-type(1) {
  height: 300px;
}

.left>div:nth-of-type(2) {
  height: 100px;
}

.right>div:nth-of-type(1) {
  height: 200px;
}

.right>div:nth-of-type(2) {
  height: 50px;
}
<div class="left" style="">
  <div style="background:red">
    1
  </div>
  <div style="background:green;">
    2
  </div>
</div>
  
<div class="right">
  <div style="background:yellow">
    3
  </div>
  <div style="background:pink">
    4
  </div>
</div>

0
Harry F. On

In fact, until a CSS technology arrives with the ability to automatically close the gaps, CSS in general has no solution. Something like this would probably require reflowing the document, so I'm not sure how useful or efficient it would be.

Source: https://stackoverflow.com/a/45200955/1625909