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

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

Linda Hamilton
Release: 2024-12-07 21:50:13
Original
675 people have browsed it

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

Force Items in Grid Last Row to Fill Space

To distribute items evenly in the last row of a CSS grid, regardless of the number of items, consider the following approach:

The challenge lies in determining the number of items in the grid to manipulate their layout. Since this may not be known beforehand, CSS provides a solution using the nth-child and nth-last-of-type selectors. Here's how it works:

  1. Identify the Last Row Items: Use nth-last-of-type to select the last row items. For example, grid > *:nth-last-of-type(1) will target all items in the last row.
  2. Distribute Left End Items: To center the leftmost item, use justify-self: center. For the second item, use justify-self: end to align it to the right. These styles can be applied to every third item (e.g., grid > *:nth-child(3n-1) and grid > *:nth-child(3n-2)).
  3. Adjust Last Item Span: For the last items in the row, we want them to span the entire remaining space. Use grid-column: span 2 or grid-column: span 3 to achieve this, depending on the number of columns in the grid (e.g., for a three-column grid, it would be grid > *:nth-child(3n-1):nth-last-of-type(1) { grid-column: span 2; }).

By combining these techniques, you can ensure that all items in the last row of your grid consume the available space evenly, regardless of their number.

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