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.
تنصل: جميع الموارد المقدمة هي جزئيًا من الإنترنت. إذا كان هناك أي انتهاك لحقوق الطبع والنشر الخاصة بك أو الحقوق والمصالح الأخرى، فيرجى توضيح الأسباب التفصيلية وتقديم دليل على حقوق الطبع والنشر أو الحقوق والمصالح ثم إرسالها إلى البريد الإلكتروني: [email protected]. سوف نتعامل مع الأمر لك في أقرب وقت ممكن.
Copyright© 2022 湘ICP备2022001581号-3