Home > Web Front-end > CSS Tutorial > How Can I Make CSS Grid's Last Row Items Fill Remaining Space?

How Can I Make CSS Grid's Last Row Items Fill Remaining Space?

Patricia Arquette
Release: 2025-01-01 11:24:10
Original
474 people have browsed it

How Can I Make CSS Grid's Last Row Items Fill Remaining Space?

Controlling Last Row Spacing in CSS Grid

Challenge:

How can we ensure that all items in the last row of a CSS grid consume the remaining space in the row, regardless of their number?

Solution:

Leveraging the power of CSS grid, we can achieve this spatial control through a clever combination of nth-child and nth-last-of-type rules. The key lies in knowing the number of columns in the grid beforehand.

Implementation:

  1. Define the grid using display: grid and specify the desired number of columns with grid-template-columns.
  2. Apply the justify-items: start property to align items in the rows.
  3. Use *:nth-child(3n-1) to style the first item in each row with specific properties (e.g., centering the text).
  4. Use *:nth-child(3n) to style the second item in each row (e.g., right-aligning the text).
  5. For the last item in each row, combine *:nth-child(3n-1) with nth-last-of-type(1) to achieve the desired spanning behavior.
  6. Add additional rules to customize the appearance of the last row, such as specifying borders or background colors.

Example Code:

.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

HTML Example:

<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

By harnessing the power of these CSS properties, we can effectively control the spacing of items in the last row of a CSS grid, ensuring an aesthetically pleasing and flexible layout.

The above is the detailed content of How Can I Make CSS Grid's Last Row Items Fill Remaining Space?. 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