1

I have a grid container with 3 items inside. I want it to be center if the 3rd item is moved to another row (like how it's displayed in the Expect section).

The wrapper's width depends on viewport's width, so I think I can use media queries here. I'm looking for an one-liner instead if possible.

My question is: how can I do that? Thanks for your time.

    .wrap {
        border: 1px solid #3498db;
        margin: 16px;
    }

    .wrap1 {
        width: 400px;
    }

    .wrap2 {
        width: 300px;
    }

    .grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
        gap: 16px;
    }

    .item {
        display: flex;
        justify-content: center;
        align-items: center;
        color: #2c3e50;
        background: #95a5a6;
        height: 50px;
    }

    .expect {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        justify-content: center;
    }
    .expect > .item {
        flex: 0 0 142px;
    }
    <div class="wrap wrap1">
        <div class="grid">
            <div class="item">
                Item 1
            </div>
            <div class="item">
                Item 2
            </div>
            <div class="item">
                Item 3
            </div>
        </div>
    </div>

    <div class="wrap wrap2">
        <div class="grid">
            <div class="item">
                Item 1
            </div>
            <div class="item">
                Item 2
            </div>
            <div class="item">
                Item 3
            </div>
        </div>
    </div>

    <span>Expect:</span>
    <div class="wrap wrap2">
        <div class="expect">
            <div class="item">
                Item 1
            </div>
            <div class="item">
                Item 2
            </div>
            <div class="item">
                Item 3
            </div>
        </div>
    </div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
hungdoansy
  • 436
  • 4
  • 10
  • Nothing a grid can do by default. you would require a 4 column grid where an item spans 2 columns. you would need to hard code the placement of the last item. Thats why you also have Flexbox which can address such issue – tacoshy Nov 25 '22 at 07:15
  • @tacoshy Can you give me some more details? I think hard-coding the last element needs media queries as well – hungdoansy Nov 25 '22 at 07:31
  • no, you dont need media queries for that but you need to know if there are an even or uneven amount of items. You could use a script for that. – tacoshy Nov 25 '22 at 07:33

0 Answers0