Home > Net >  CSS grid has empty items
CSS grid has empty items

Time:12-26

I am trying to force the items in column 2 to be in the same rows as the corresponding items in column 1. The 'A' items to be in the first row, 'B' items in the second row, etc.

I thought that by assigning grid-column to my items that it would force the items into the columns and then fill in any blanks. But instead it's leaving empty space.

How do I explicitly set the column number without leaving empty items?

enter image description here

https://codepen.io/ohthepain/pen/JjBYaVo

.grid-container {
  display: grid;
  gap: 1rem;
}

.grid-item {
  background-color: skyblue;
}

.grid-column-1 {
  grid-column: 1;
}

.grid-column-2 {
  grid-column: 2;
}
<!DOCTYPE html>

<head>
  <link rel="stylesheet" href="./index.css" />
</head>

<body>
  <div>
    <div >
      <div >
        Column 1 A
      </div>
      <div >
        Column 1 B
      </div>
      <div >
        Column 1 C
      </div>
      <div >
        Column 2 A
      </div>
      <div >
        Column 2 B
      </div>
      <div >
        Column 2 C
      </div>
    </div>
  </div>
</body>

</html>

CodePudding user response:

This is what you need to do, this is the updated CSS

.grid-container {
    display: grid;
    gap: 1rem;
    grid-template-columns: 4fr 4fr;
}

Overall you have this.

.grid-container {
    display: grid;
    gap: 1rem;
    grid-template-columns: 4fr 4fr;
}

.grid-item {
    background-color: skyblue;
}
<!DOCTYPE html>
<head>
    <link rel="stylesheet" href="./index.css"/>
</head>
<body>
    <div>
        <div >
            <div >
                Column 1 A
            </div>
            <div >
                Column 2 A
            </div>
            <div >
                Column 1 B
            </div>
            <div >
                Column 2 B
            </div>
            <div >
                Column 1 C
            </div>
            <div >
                Column 2 C
            </div>
        </div>
    </div>
</body>
</html>

CodePudding user response:

Use this below code and you can fulfill your requirement.

.grid-container {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(6, auto);
  grid-template-rows: auto auto auto;
  grid-auto-flow: column;
}
.grid-item {
  background-color: skyblue;
  font-size: 24px;
}
<div >
  <div >
    Column 1 A
  </div>
  <div >
    Column 1 B
  </div>
  <div >
    Column 1 C
  </div>
  <div >
    Column 2 A
  </div>
  <div >
    Column 2 B
  </div>
  <div >
    Column 2 C
  </div>
</div>

  • Related