neither FLEX nor GRID can't do what's needed

Viewed 50

I'm trying to solve a simple task but the solutions seem not be that simple. Basically, I want many blocks with the same size to be aligned in center but I nee 1 block that is twice bigger than the others. If I use FLEX - there are blank spaces around the big block. If I use GRID - I can't align the blocks in the center. Please help!

    #all {
    width: 100%;
    border: 1px solid #ff0000;
    display: grid;
    grid-gap: 10px;
    grid-template-columns: repeat(auto-fill, 150px);
    grid-template-rows: repeat(auto-fill, 150px);
    }
    #all div {
    width: 150px; height: 150px;
    border: 1px solid #ff0000;
    }
    #all .big {
    width: 310px; height: 312px;
    grid-column: 2/ 4;
    grid-row: 2 / 4;
    }
<html>
<head>
<style>

</style>
</head>

<body>
    <div id=all>
        <div></div>
        <div></div>
        <div class=big></div>
        <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
    </div>
</body>
</html>

I need them to be aligned in the center

1 Answers

Here is an edited answer from W3Schools.

NOTE: there must be enough items to circle the one in the middle.

First, you need to add odd items in the grid. Then, add odd columns to align them properly as you want. Last, use grid-area to start any of the items from the 2nd row and column. then end it at the other corner according to the number of items in the grid.

and the good thing about this is that it's responsive and you can select any item to put it in the middle.

here is the code.

.grid-container {
    display: grid;
    grid-template-columns: auto auto auto ; /* odd column */
    gap: 10px;
    background-color: #2196F3;
    padding: 10px;
  }
  
  .grid-container > div {
    background-color: rgba(255, 255, 255, 0.8);
    text-align: center;
    padding: 20px 0;
    font-size: 30px;
  }
  
  .item5 {
    grid-area: 2 / 2 / 4 / 3; /* start and end the selected item */
    display: flex;
    justify-content: center;
    align-items: center;
  }
<h1>The grid-column Property</h1>

<p>Use the <em>grid-column</em> property to specify where to place an item.</p>

<div class="grid-container">
<!--  add odd items in the grid -->
  <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 class="item10">10</div>
  <div class="item11">11</div>
</div>

Related