Home > Software design >  Dealing with 2 items in a row when you have 3 columns
Dealing with 2 items in a row when you have 3 columns

Time:05-27

In a 3 column grid if the last line has only 2 items is it possible to have them laid out like the attached image? Is this possible using just CSS and not adding a blank entry?

enter image description here

<!DOCTYPE html>
<html>
<head>
<style>
.grid-container {
  display: grid;
  grid-template-columns: auto auto auto;
  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;

  
}


}
</style>
</head>
<body>

<h1>Grid Lines</h1>

<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>  
  <div >4</div>
  <div >5</div>
  <div >6</div>
  <div >7</div>
  <div >8</div>
</div>

<p>You can refer to line numbers when placing grid items.</p>

</body>
</html>

CodePudding user response:

You have a repeating pattern of 3 elements (3n)

You want the last element :last-child to be in the third column if it stands in the second div:nth-child(3n - 1).

the rules together would be div:nth-child(3n - 1):last-child.

Demo below

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto;
  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;
}

/* if last div is standing in the second column out of three, move it to third */
.grid-container>div:nth-child(3n - 1):last-child {
  grid-column: 3
}
<h1>Grid Lines</h1>

<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
  <div >6</div>
  <div >7</div>
  <div >8</div>
</div>
<hr>
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
  <div >6</div>
  <div >7</div>
  <div >8</div>
  <div >9</div>
</div>
<hr>
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
</div>
<hr>
<div >
  <div >1</div>
  <div >2</div>
</div>

CodePudding user response:

Because you have an explicit grid you can allow a specific child to span all columns by using grid-column: -2 / -1; on your last child. This tells the grid area to span from the third column line to the last column line, effectively getting space-between on the last row.

See below:

.grid-container {
  display: grid;
  grid-template-columns: auto auto auto;
  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;
}

.grid-container>div:last-child {
  grid-column: -2 / -1;
}
<h1>Grid Lines</h1>

<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
  <div >6</div>
  <div >7</div>
  <div >8</div>
</div>

<p>You can refer to line numbers when placing grid items.</p>

  • Related