Reputation: 43
Why do I have an overflow on the X axis in the following snippet?
The overflow is generated once I apply grid-gap: 35px on my .box grid container.
.container {
width: 500px;
border: 1px solid #000;
margin: 0 auto;
}
.box {
display: grid;
grid-template-columns: repeat(16, 1fr);
background: #00f;
gap: 35px;
}
.item {
height: 50px;
background: #0f0;
text-align: center;
line-height: 40px;
vertical-align: middle;
}
.span4 {
grid-column: span 4;
}
<div class="container">
<div class="box">
<div class="item span4">A</div>
<div class="item span4">B</div>
<div class="item span4">C</div>
<div class="item span4">D</div>
<div>
</div>
Upvotes: 4
Views: 1704
Reputation: 54
Since you have 4 div elements of class="item", in .box
you can reduce the number of columns to 4
grid-template-columns: repeat(4, 1fr);
where each .item
element spans 1 column.
grid-column: span 1;
This fixes the overflow problem.
As to why this happens:
For a certain column width, the column gap is supposed to take up a percentage of the column. If the column gap is smaller than the column width, then the column gap is by default included in the column. If the column gap is larger than the column width, then the column cannot hold the column gap and has no choice but to overflow. Since the column width which is 500/16 = 31.25 is smaller than the column gap 35, it overflows.
Note: this only seems to happen when an element is spamming more than one column. If an element is spanning one column and the the column gap is greater than column width, then it is constrained at the given column width. Hope this helped :)
Hope this helped :)
Upvotes: 0
Reputation: 1808
This is because a Grid item(i.e. .container
) cannot be smaller than it's contents(all .item
combined). Let's consider your case here.
container width = 500px
grid-template-columns
is repeating 16 times with gap
of 35px
each. If we do the math here that would be 560px
(16*35) which will be greater than your container width(500px
).
To fix this either you increase the container width to 560px
or make in percentages i.e. 100%
.container {
width: 100%; /*560px*/
border: 1px solid #000;
margin: 0 auto;
}
.box {
display: grid;
grid-template-columns: repeat(16, 1fr);
background: #00f;
gap: 35px;
}
.item {
height: 50px;
background: #0f0;
text-align: center;
line-height: 40px;
vertical-align: middle;
}
.span4 {
grid-column: span 4;
}
<div class="container">
<div class="box">
<div class="item span4">A</div>
<div class="item span4">B</div>
<div class="item span4">C</div>
<div class="item span4">D</div>
<div>
</div>
Upvotes: 2