Home > Web Front-end > CSS Tutorial > How to Equally Distribute Items in the Last Row of a CSS Grid?

How to Equally Distribute Items in the Last Row of a CSS Grid?

Patricia Arquette
Release: 2024-12-10 06:14:10
Original
317 people have browsed it

How to Equally Distribute Items in the Last Row of a CSS Grid?

CSS Grid: Distributing Last Row Items Equally

In our web design endeavors, there often arises the need to evenly distribute items within a grid layout, particularly in the final row. This task is easily accomplished with the combined power of nth-child and nth-last-of-type rules. However, a prerequisite for this method is knowing the number of columns in your grid.

Consider the following markup:

<div class="grid">
  <div>text</div>
  <div>TEXT</div>
  <div>text</div>
  <div>text</div>
  <div>TEXT</div>
  <div>text</div>
  <div>text</div>
  <div>TEXT</div>
</div>
Copy after login

And these accompanying CSS rules:

.grid {
    display: grid;
    grid-template-columns: auto auto auto;
    justify-items: start;
    grid-gap: 10px;
}

.grid div {
  border: 1px solid #ccc;
  width: 100%;
}

.grid > *:nth-child(3n-1) {
  justify-self: center;
  text-align: center;
}

.grid > *:nth-child(3n) {
  justify-self: end;
  text-align: right;
}

.grid > *:nth-child(3n-1):nth-last-of-type(1) {
  border-color: red;
  grid-column: span 2;
}

.grid > *:nth-child(3n-2):nth-last-of-type(1) {
  border-color: red;
  grid-column: span 3;
}
Copy after login

In this example, a grid is defined with three columns, and we specify the distribution and styling of the items within the last row using nth-child and nth-last-of-type. The borders are added to demonstrate the visual effect.

The css rules applied to nth-child(3n-1):nth-last-of-type(1) or nth-child(3n-2):nth-last-of-type(1) ensures that the last items in the second and third columns will span two or three columns, respectively and aesthetically consume the remaining space in the row.

The above is the detailed content of How to Equally Distribute Items in the Last Row of a CSS Grid?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template