Search code examples
htmlcssgrid-layoutcss-grid

CSS Grid: Don't expand grid items


I'm creating a design for mobile and for desktop. When on mobile, all elements are stack on top of each other. When on desktop, elements are in 2 columns. Elements have different order when on mobile and on desktop.

enter image description here I thought of creating that using CSS grid.

HTML

<div class="grid-release">
    <div class="gi-cover">cover</div>
    <div class="gi-detail">detail</div>
    <div class="gi-head">head </div>
    <div class="gi-desc">desc</div>
    <div class="gi-media">media</div>
    <div class="gi-comment">comment</div>
</div>

CSS

.grid-release {
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: auto;
    grid-template-areas:
    "head"
    "cover"
    "detail"
    "desc"
    "media"
    "comment";
    grid-gap: 10px;
}

.grid-release .gi-cover {
    grid-area: cover;
    background-color: red;
}
.grid-release .gi-detail {
    grid-area: detail;
    background-color: yellow;
}

.grid-release .gi-head {
    grid-area: head;
    background-color: cyan;
}
.grid-release .gi-desc {
    grid-area: desc;
    background-color: chartreuse;
}
.grid-release .gi-media {
    grid-area: media;
    background-color: orange;
}

.grid-release .gi-comment {
    grid-area: comment;
    background-color: darkkhaki;
}

@media screen and (min-width: 400px) {
    .grid-release {
        grid-template-columns: 1fr 2fr;
        grid-template-rows: auto;
        grid-template-areas:
        "cover head"
        "detail desc"
        ". media"
        ". comment"; 
    }
}

... and the result:

https://jsfiddle.net/q3hpr0ak/

Here's my problem. When on desktop and the cover grid item expands, so does the head grid item.

https://jsfiddle.net/z5jhewhb/1/

When the detail grid item expands, so does the desc grid item

https://jsfiddle.net/Lh2y2pzp/2/

and so on...

Obviously, that creates a very ugly layout. I'm starting to think that maybe CSS grid is the wrong approach. I need guidance. I've been playing with this all morning with no success.


Solution

  • I just gave this a second thought... and the asnwer couldn't be simpler: use good ol' floats for desktop, flex for mobile so you can re-order items as needed:

    @media screen and (min-width: 700px) {
      .container { display:block; }
      .cover, .detail{ width:33%; }
      .head, .desc, .media, .comment { width:66%; float:right; }
    }
    

    https://jsfiddle.net/q3hpr0ak/3/

    check the jsfiddle, I think it'll work just fine this time ;)