Home > Web Front-end > CSS Tutorial > Why Doesn\'t My Grid Item\'s Percentage Height Work as Expected?

Why Doesn\'t My Grid Item\'s Percentage Height Work as Expected?

DDD
Release: 2024-11-27 09:52:13
Original
579 people have browsed it

Why Doesn't My Grid Item's Percentage Height Work as Expected?

Why Grid Element Height Fails When Calculated as Percentage of Parent Height

CSS Grid's height calculation can be confusing, especially when using percentages. In the example provided, the grid item's height is set to 200%, but it doesn't double the height of the container.

Understanding Grid Hierarchy

A grid item resides within a track, which is contained within the container. Therefore, the parent of the grid item is the track, not the container directly.

Percentage Height and Grid Structure

When a grid row's height is not defined as a fixed unit of length (e.g., px) or calculated as a fraction of the available space (e.g., 1fr), the grid item's percentage height fails. In this case, the grid item's height defaults to auto, effectively allowing it to expand the row as needed.

Setting Container and Row Height

To ensure the grid element's height is based on the container's height, set a fixed height on both the container and the row. In the provided code, the container height was 100px, but the row height was set to 1fr. By changing the row height to 100px, the grid item's 200% height will correctly double the height of the container.

Updated Example:

.gridContainer {
  // ...
  grid-template-rows: 100px;
}

.gridItem {
  // ...
  overflow: auto;
}
Copy after login

By adjusting the row height to match the container height, the grid item's height will now behave as expected, doubling the height of the container and correctly wrapping the content inside it.

The above is the detailed content of Why Doesn\'t My Grid Item\'s Percentage Height Work as Expected?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template