Home  >  Article  >  Web Front-end  >  Why Does Display Grid with 100% in Grid-template-columns Exceed the Body?

Why Does Display Grid with 100% in Grid-template-columns Exceed the Body?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 04:39:27571browse

Why Does Display Grid with 100% in Grid-template-columns Exceed the Body?

Why does Display Grid with 100% in Grid-template-columns Exceed the Body?

In the provided CSS code:

<code class="css">.parent {
  position: fixed;
  width: 100%;
  left: 0;
  top: 14px;
  display: grid;
  grid-template-columns: 40% 60%;
  grid-gap: 5px;
  background: #eee;
}</code>

The issue arises not from the width: 100% property but from the grid-template-columns setting. When specifying percentages (40% and 60%) and a grid gap (5px), the total width exceeds 100%. This causes the parent container to extend beyond the body's right edge when positioned fixed.

Solution: Using the fr Unit

To resolve this issue, it's recommended to use fractional units (fr) instead of percentages for the grid-template-columns declaration. Fractional units allocate space proportionally, considering any defined gaps:

<code class="css">.parent {
  ...
  grid-template-columns: 4fr 6fr;
  ...
}</code>

Example:

<code class="html"><div class='parent'>
  <div class='left'>LEFT</div>
  <div class='right'>RIGHT</div>
</div></code>

With this modification, the parent container will now be fully visible within the body's boundaries, even when positioned fixed.

The above is the detailed content of Why Does Display Grid with 100% in Grid-template-columns Exceed the Body?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn