Home > Web Front-end > CSS Tutorial > 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?

Mary-Kate Olsen
Release: 2024-11-02 09:07:02
Original
675 people have browsed it

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:



.parent {<br>  position:fixed;<br>  width:100%;<br>  left:0;<br>  top:14px;<br>  display:grid;<br>  grid-template-columns:40% 60%;<br>  grid-gap:5px;<br>  background:#eee;<br>}<br>.left {<br>  border:2px solid red;<br>}<br>.right {<br>  border:2px solid red;<br>}

<div class='parent'><br>  <div class='left'>LEFT</div><br>  <div class='right'>RIGHT</div><br></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:



.parent {<br>  position:fixed;<br>  width:100%;<br>  left:0;<br>  top:14px;<br>  display:grid;<br>  grid-template-columns:4fr 6fr;<br>  grid-gap:5px;<br>  background:#eee;<br>}<br>.left {<br>  border:2px solid red;<br>}<br>.right {<br>  border:2px solid red;<br>}

<div class='parent'><br>  <div class='left'>LEFT</div><br>  <div class='right'>RIGHT</div><br></div>

By using fr units, the grid will now distribute the space correctly, ensuring that it remains within the bounds of the body.

The above is the detailed content of Why does a grid with 100% grid-template-columns extend beyond the body when using fixed positioning?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template