When working with CSS Grid or Flexbox, it is possible to set a size limit for siblings using one item as a reference. This means that the size of all other siblings will be defined in relation to the reference item, creating a layout that is both flexible and consistent.
Syntax: To set a size limit for siblings in CSS Grid or Flexbox, you can use the following syntax:
For Grid:
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: 1fr 2fr 1fr;
}
.grid-item {
grid-column: 2 / 3;
height: 100%;
}
For Flexbox:
.flex-container {
display: flex;
flex-wrap: wrap;
height: 100%;
}
.flex-item {
flex: 1 0 25%;
}
Approaches: There are two approaches to setting a size limit for siblings in CSS Grid or Flexbox.
Approach 1: This approach is to use a fixed size for the reference item. This means that all other siblings will be limited to the same size, creating a consistent layout.
Example: Fixed Size Reference Item
<!DOCTYPE html>
<html>
<head>
<title>
Example with Fixed Size Reference Item
</title>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: 1fr 2fr 1fr;
}
.grid-item {
background-color: #cfc9c9;
padding: 7px;
text-align: center;
}
.reference-item {
grid-column: 2 / 3;
height: 80px;
}
</style>
</head>
<body>
<center>
<h1 style="color: green;">
Geeks for Geeks
</h1>
</center>
<div class="grid-container">
<div class="grid-item reference-item">
<h1>Reference Item</h1>
</div>
<div class="grid-item">
<h1> Sibling 1</h1>
</div>
<div class="grid-item">
<h1>Sibling 2</h1>
</div>
<div class="grid-item">
<h1> Sibling 3</h1>
</div>
</div>
</body>
</html>
Output:
.png)
Approach 2: This approach is to use a relative size for the reference item. This means that all other siblings will be limited to a percentage of the reference item, creating a flexible layout.
Example: Relative Size Reference Item
<!DOCTYPE html>
<html>
<head>
<title>
Example with Relative Size Reference Item
</title>
<style>
.flex-container {
display: flex;
flex-wrap: wrap;
height: 100%;
}
.flex-item {
background-color: #eee;
padding: 10px;
text-align: center;
}
.reference-item {
flex: 1 0 50%;
}
</style>
</head>
<body>
<center>
<h1 style="color: green;">
Geeks for Geeks
</h1>
</center>
<div class="flex-container">
<div class="flex-item reference-item">
<h1>Reference Item</h1>
</div>
<div class="flex-item">
<h1> Sibling 1</h1>
<div class="flex-item">
<h1>Sibling 2</h1>
</div>
<div class="flex-item">
<h1> Sibling 3</h1>
</div>
</div>
</body>
</html>
Output:
.png)