Issue Specific to Chrome Browser
For the auto-fit and auto-fill functionalities to work properly, a known width is necessary for calculation. This can be achieved by using max-width:100%
instead of width
to ensure proper centering without stretching or fixed widths.
.box {
box-sizing: border-box;
width: 200px;
height: 150px;
background-color: white;
border: solid 6px red;
}
.box:nth-child(2) {
background-color: blue
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, 200px);
max-width: 100%;
}
.center {
display: flex;
flex-direction: column;
align-items: center;
}
<div class="center">
<div class="grid">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
Note that if the initial viewport is wide and then resized smaller, the grid may not remain centered due to issues with auto-fill
.
In cases where there are fewer elements than the container can fit columns due to auto-fill
, uneven spacing may occur. Using auto-fit
ensures even distribution when an element is missing.
.box {
box-sizing: border-box;
width: 200px;
height: 150px;
background-color: white;
border: solid 6px red;
}
.box:nth-child(2) {
background-color: blue
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, 200px);
max-width: 100%;
}
.center {
display: flex;
flex-direction: column;
align-items: center;
}
<div class="center">
<div class="grid">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
To address spacing inconsistencies upon resizing due to relative units in max-width calculations, triggering a recalculation through animation can solve this issue.
Solution Specifically for Chrome Browser
.center {
display: flex;
flex-direction: column;
align-items: center;
}
.box {
box-sizing: border-box;
width: 200px;
height: 150px;
background-color: white;
border: solid 6px red;
}
.box:nth-child(2) {
background-color: blue
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, 200px);
max-width: 100%;
animation: recalc 5s linear infinite;
}
@keyframes recalc {
to {
max-width: 99.9%;
}
}
<div class="center">
<div class="grid">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
To ensure compatibility with Firefox and other browsers, consider using viewport units for defining widths.
.box {
box-sizing: border-box;
width: 200px;
height: 150px;
background-color: white;
border: solid 6px red;
}
.box:nth-child(2) {
background-color: blue
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, 200px);
max-width: 100vw;
margin:0 auto;
}
.center {
display: flex;
}
<div class="center">
<div class="grid">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>