Reputation:
I'm trying to build a UI which has the section be display:grid with a grid-template-columns: 1fr 3fr.
Then I have 2 block elements that should be placed in those columns (I used grid-column: 1/2 and grid-column: 2/3), respectively.
Now, my issue is that I wanted the block on the left (in the 1fr cell/area) to have a fixed-position. It's supposed to be a persistent navigation sidebar. However, when I used position: fixed, the block is removed entirely from the grid and so responsiveness doesn't really factor in anymore.
I tried nesting a container inside the main grid-item and giving that one the fixed-position, but when I adjusted my viewport to test, the fixed-container just overflowed/overlapped onto the 3fr block.
Any ideas on who to pull this off?
Thanks!
Upvotes: 0
Views: 4421
Reputation: 347
Hello i had this problem too, and the solution i came up with and it's working :) just wrap the div that you want with a grid layout with another div lets call it parent, the parent div will be the grid element and the div inside will be with the position fixed!
.parent{
// This div will be from the grid children
}
.child {
position:fixed;
}
Upvotes: 2
Reputation: 115108
Perhaps position:sticky
instead.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
::before,
::after {
box-sizing: inherit;
}
.grid {
display: grid;
grid-template-columns: 1fr 3fr;
grid-gap: .5em;
}
aside {
padding: 0 .5em;
background: lightblue;
}
main {
grid-column: 2;
height: 500vh;
background: lightgreen;
}
aside div {
position: sticky;
top: 0;
}
<div class="grid">
<aside>
<div>
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
<li>item 5</li>
<li>item 6</li>
<li>item 7</li>
<li>item 8</li>
<li>item 9</li>
<li>item 10</li>
</ul>
</div>
</aside>
<main>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit provident, voluptatem, dolor eligendi quos harum reiciendis accusantium sapiente optio ad suscipit ullam, quibusdam aut ipsam laboriosam itaque eius officiis. Sapiente molestias vero aut
deleniti vitae cupiditate praesentium necessitatibus delectus, incidunt, cumque porro molestiae ipsa quas eveniet quisquam quod ipsam? Earum.</main>
</div>
The page still scrolls but the div in the sidebar remains "stuck" to the top
Upvotes: 2
Reputation: 309
If you want the element to remain a grid item, then the answer is "you can't".
Once an element has position: absolute
or position: fixed
(which is a form of absolute positioning, with reference to the viewport), it takes on new characteristics:
So a grid item doesn't work well with fixed positioning.
However, you won't have a problem applying position: fixed
to a grid container.
Consider managing your #left
and #right
elements separately. #left
can be a fixed-position grid container. #right
can be another grid container and remain in-flow.
Upvotes: 2