Im trying to get multiple divs with diffrenent heights to use their given space.
The problem within my example is that there are still some empty space wich is not filled.
My Code looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Optimal Grid Layout with Variable Heights</title>
<style>
body, html {
margin: 0;
padding: 0;
height: 100%;
}
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-template-rows: repeat(auto-fit, minmax(1fr, 1fr));
gap: 10px;
height: 100vh;
padding: 10px;
box-sizing: border-box;
grid-auto-flow: dense;
}
.item {
background-color: lightblue;
border: 1px solid #000;
padding: 20px;
text-align: center;
box-sizing: border-box;
}
.item:nth-child(1) {
height: 150px;
}
.item:nth-child(2) {
height: 200px;
}
.item:nth-child(3) {
height: 250px;
}
.item:nth-child(4) {
height: 300px;
}
.item:nth-child(5) {
height: 350px;
}
.item:nth-child(6) {
height: 400px;
}
</style>
</head>
<body>
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
</div>
</body>
</html>
2
Answers
To create a CSS grid layout without empty spaces using grid-template-columns and grid-template-rows, you need to ensure that all the grid items are properly placed within the defined grid areas. This can be achieved by either explicitly placing the items using grid lines or allowing the grid to auto-place the items. Here are some examples demonstrating these concepts.
Example 1: Explicit Grid Placement
In this example, each grid item is explicitly placed in a specific cell using grid-column and grid-row.
html
Example 2: Auto-Placement with Grid Auto Flow
In this example, grid items are automatically placed into the grid without specifying grid lines. The grid-auto-flow property is used to control the auto-placement.
html
Example 3: Responsive Grid with Media Queries
This example demonstrates how to create a responsive grid layout that adapts to different screen sizes without empty spaces.
html
In this example, grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); ensures that the grid items fill the available space and wrap to the next row as needed, maintaining a responsive layout without empty spaces.
These examples should help you create a CSS grid layout that efficiently uses space without leaving gaps or empty spaces.
If I understand you correctly you just want to change
height
tomin-height
.