Home > Web Front-end > CSS Tutorial > How Can I Make the Last Row in a CSS Grid Span the Entire Row?

How Can I Make the Last Row in a CSS Grid Span the Entire Row?

Linda Hamilton
Release: 2024-12-21 09:03:11
Original
652 people have browsed it

How Can I Make the Last Row in a CSS Grid Span the Entire Row?

Filling the Last Row in CSS Grid

In CSS Grid, a common challenge is to ensure that items in the last row occupy the entire row. Without knowing the exact number of items, solutions may seem elusive.

Using nth-child and nth-last-of-type

This can be achieved using a combination of CSS rules: nth-child and nth-last-of-type. These rules target elements based on their position within a specific parent element. With these rules, it's possible to adjust the alignment and sizing of items in the last row.

Sample Code:

Consider the following CSS 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

Explanation:

  • nth-child(3n-1) and nth-child(3n) target elements based on their position within the grid container. These rules are used to style items in the middle and right columns.
  • nth-child(3n-1):nth-last-of-type(1) and nth-child(3n-2):nth-last-of-type(1) specifically target the last item in the last row and adjust its alignment and spanning.
  • The grid-column property is used to control the column span of these last items, ensuring they fill the entire row.

The above is the detailed content of How Can I Make the Last Row in a CSS Grid Span the Entire Row?. 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