Issue: Optimizing Box Sizes in Flexbox/Grid Layouts for Balanced Design

Screenshot from 2024-08-14 15-26-40
I want to create this design. However, when using Flexbox or Grid, the smaller blue boxes take more space than the others. How can I solve this issue?

Use a grid layout and make sure you define the column width as 1fr for each column so they are all the same.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .grid-container {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            grid-template-rows: repeat(3, 1fr);   

        }
        
        .grid-container div {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            font-size: 18px;
        }

      
        .item1, .item5, .item9 {
            grid-row: span 1;
            height: 50px;  
            margin-left: 10px; 
            margin-right: 10px; 
            background-color: dodgerblue;
        }

        .item2, .item3, .item4, .item6, .item7, .item8 {
            height: 100px;   
            margin: 10px 10px;
            background-color: black;
            color: #ddd;
        }
        
        /* Specific grid placements */
        .item1 { grid-column: 1; grid-row: 1; }
        .item2 { grid-column: 1; grid-row: 2; }
        .item3 { grid-column: 1; grid-row: 3; }
        .item4 { grid-column: 2; grid-row: 1; }
        .item5 { grid-column: 2; grid-row: 2; }
        .item6 { grid-column: 2; grid-row: 3; }
        .item7 { grid-column: 3; grid-row: 1; }
        .item8 { grid-column: 3; grid-row: 2; }
        .item9 { grid-column: 3; grid-row: 3; }
        
    </style>
</head>
<body>
    <div class="grid-container">
        <div class="item1">1</div>
        <div class="item2">2</div>
        <div class="item3">3</div>
        <div class="item4">4</div>
        <div class="item5">5</div>
        <div class="item6">6</div>
        <div class="item7">7</div>
        <div class="item8">8</div>
        <div class="item9">9</div>
    </div>    
</body>
</html>

I also try to fix it manually without using gap property but problem is not solved. Always showing output as this image.

hi there!

remove margin from .item1 and .item2, then add some gap in .gird-container .

  • Grid: You create a grid layout with two columns and three rows. The black boxes fill the space, and the blue boxes have fixed sizes.
  • Flexbox: You create a flexible container that wraps items into lines. The black boxes fill half the container’s width, and the blue boxes have fixed sizes.