Grid Exceeds Body with 100% Grid-Template-Columns
Why does a display grid with 100% in grid-template-columns extend beyond the body when position is set to fixed?
Problem:
Consider the following CSS and HTML:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override">.parent {
position:fixed;
width:100%;
left:0;
top:14px;
display:grid;
grid-template-columns:40% 60%;
grid-gap:5px;
background:#eee;
}
.left {
border:2px solid red;
}
.right {
border:2px solid red;
}</pre>
<pre class="snippet-code-html lang-html prettyprint-override"><div class='parent'>
<div class='left'>LEFT</div>
<div class='right'>RIGHT</div>
</div></pre>
</div>
When position is not fixed, the grid displays correctly. However, when position is set to fixed, the grid extends beyond the body on the right side.
Solution:
The issue lies not with the 100% width but with the grid-template-columns property. Using percentages and a fixed grid-gap will exceed 100% of the available space.
Instead, rely on the fr unit to distribute the free space proportionally, taking into consideration the grid gap:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override">.parent {
position:fixed;
width:100%;
left:0;
top:14px;
display:grid;
grid-template-columns:4fr 6fr;
grid-gap:5px;
background:#eee;
}
.left {
border:2px solid red;
}
.right {
border:2px solid red;
}</pre>
<pre class="snippet-code-html lang-html prettyprint-override"><div class='parent'>
<div class='left'>LEFT</div>
<div class='right'>RIGHT</div>
</div></pre>
</div>
By using fr units, the grid will now distribute the space correctly, ensuring that it remains within the bounds of the body.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3