3

There are 3 items in the grid container. I want to center the 3rd div which is overflowing because the first two divs take 50% of the space.

#gridContainer{
display: grid;
grid-template-columns: 50% 50%;
grid-template-rows: 50% 50%;
grid-gap: 1%;
}
<div id="gridContainer">
  <div >1</div>
  <div>2</div>
  <div>3 - center in next row</div>
</div>
Alan M
  • 616
  • 5
  • 15

3 Answers3

3

According to docs of Box alignment in CSS Grid Layout, you can use grid-template-areas.

#gridContainer{
     display: grid;
     grid-template-columns: repeat(4, 1fr);
     grid-auto-rows: 50px;
     grid-gap: 1%;
     grid-template-areas: "a a b b" ". c c .";
}
#gridContainer > div{
     border:1px solid red;
}
.item1{
     grid-area: a;
}
.item2{
     grid-area: b;
}
.item3{
     grid-area: c;
}
 
<div id="gridContainer">
        <div class="item1">1</div>
        <div class="item2">2</div>
        <div class="item3">3 - center in next row</div>
      </div>
Mickael Lherminez
  • 679
  • 1
  • 10
  • 29
Marios Nikolaou
  • 1,326
  • 1
  • 13
  • 24
1

The tool you could use (because it is probably more suitable to this task) is the flexbox. Here is the simple code example:

#flexContainer {
  display: flex;
  flex-wrap: wrap;
}

#flexContainer div {
  flex-grow: 1;
  flex-basis: 50%;
  text-align: center;
  box-sizing: border-box;
  border: 1px solid white;
  background-color: #CCC;
}
<div id="flexContainer">
  <div>1</div>
  <div>2</div>
  <div>3 - center in next row</div>
</div>

I am not sure if this is what you meant though. If you didn't want to make the third div take the full width of the row, it is possible too:

#flexContainer {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

#flexContainer div {
  flex-basis: 50%;
  text-align: center;
  box-sizing: border-box;
  border: 1px solid white;
  background-color: #CCC;
}
<div id="flexContainer">
  <div>1</div>
  <div>2</div>
  <div>3 - center in next row</div>
</div>
ajobi
  • 2,996
  • 3
  • 13
  • 28
0

You can either use grid-template-areas or do as the code below:

#gridContainer{
  display: grid;
  grid-template-columns: repeat(4 , minmax(100px, 1fr));
  grid-template-rows: repeat(2, 1fr);
  grid-gap: 1%;
}

#gridContainer div{
  background: #ccc;
  margin-bottom: 10px;
  text-align: center;
}

.first{
  grid-column: 1 / 3;
}

.second{
  grid-column: 3 / 6;
}

.third{
  grid-column: 2 / 4;
}
<div id="gridContainer">
  <div class="first">1</div>
  <div class="second">2</div>
  <div class="third">3 - center in next row</div>
</div>
elahe karami
  • 641
  • 5
  • 11