「労働者が自分の仕事をうまくやりたいなら、まず自分の道具を研ぎ澄まさなければなりません。」 - 孔子、「論語。陸霊公」
表紙 > プログラミング > Why does a grid with 100% grid-template-columns extend beyond the body when using fixed positioning?

Why does a grid with 100% grid-template-columns extend beyond the body when using fixed positioning?

2025-05-06に投稿
ブラウズ:590

Why does a grid with 100% grid-template-columns extend beyond the body when using fixed positioning?

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