Search code examples
htmlcssflexboxcss-gridcss-float

How to have independent column heights in HTML CSS grid?


I'm trying to create the following layout on desktop:

enter image description here

And have it responsively adjust to this on mobile (notice members comes before posts):

enter image description here

And I cannot figure it out. For example, if I have this:

.container {
  display: grid;
  grid-template-columns: 1fr;
  grid-auto-rows: auto;
  gap: 1rem;
  max-width: 600px;
  margin: 0 auto;
}

.title, .members, .posts {
  padding: 1rem;
  background: #f1f1f1;
}

@media (min-width: 768px) {
  .container {
    grid-template-columns: 2fr 1fr;
    gap: 1rem;
    align-items: start;
  }

  .members {
    grid-column: 2;
    grid-row: 1 / -1;
  }
}
<div class="container">
  <div class="title">Title goes here</div>
  <div class="members">Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here</div>
  <div class="posts">Posts go here</div>
</div>

Then there's a large gap between the title and posts on desktop, whereas I want it to flow freely and have each item only be as large as it needs to be. Can this be done? Feel free to change the HTML to make it work (or not even use grid if there's a better way). No javascript please


Solution

  • Since you are relying on media queries it means you can control when the layout will change. You can try the below

    .container {
      display: grid;
      gap: 1rem;
      max-width: 600px;
      margin: 0 auto;
    }
    
    .title, .members, .posts {
      grid-column: 1;
      padding: 1rem;
      background: #f1f1f1;
    }
    
    @media (min-width: 768px) {
      .container {
        grid-template-columns: auto 1fr 300px; /* update the 300px like you want */
      }
      .members {
        grid-column: 3;
        grid-row: span 3;
      }
    }
    <div class="container">
      <div class="title">Title goes here</div>
      <div class="members">Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here Members list here</div>
      <div class="posts">Posts go here</div>
    </div>