DEV Community

Cover image for Scrollable layout with height 100%
Harsh boricha
Harsh boricha

Posted on • Updated on

Scrollable layout with height 100%

Hello there 👋🏼, internet users. Today, I'll show you a CSS trick I frequently forget about when creating scrollable dynamic height layouts. Recently, I was developing a basic layout similar to one below. It took me a while to remember this trick, but once I did, I had a sense of deja vu and finished the layout.

There are two way to achieve this:

Way 1: Using css positions:

If you look at the code above, you'll see what I mean. As you can see, there's a NAVBAR, a BREADCRUMB BAR, the MAIN SECTION, and a FOOTER all contained within a layout container with the height of height: 100vh. I wanted the sidebar and content-box in my main section to be scrollable.

I could set the height as a fixed value, something like height: 800px with overflow-y: scroll but then making the layout responsive will become a nightmare.

So, the question arises? 🤔. How can we apply the overflow-y: scroll attribute to a div with a height of 100 percent?

The solution 🧪 here is to use position: relative for the main section container and position: absolute for the sidebar and content bar, with overflow-y: scroll.

.main {
position: relative;
height: 100%;
}

.sidebar {
position: absolute; 
top: 0;
left: 0;
bottom: 0;  /*stretch from top to bottom w.r.t .main section*/
width: 10rem;
overflow-y: scroll;
}

.content {
position: absolute;
top: 0;
left: 10rem;
bottom: 0;
right: 0; /* stretch from top to bottom, and shift 10rem from left and stretch till right */
overflow-y: scroll;
}
Enter fullscreen mode Exit fullscreen mode

There are many other ways, to achieve this. It's just a trick i often use. If you have any alternate way please comment (I'm all 👂). Congratulations 🎉 for reading this. Hope this might help you. Thank you.

After many of you suggested there's a neat way to do this avoiding css positions. I've added another solution using css grid.

Way 2: Using css grid

Oldest comments (6)

Collapse
 
ivan_jrmc profile image
Ivan Jeremic

CSS Grid with 100vh 😉

Collapse
 
harshboricha98 profile image
Harsh boricha • Edited

Hey, Thank you for your suggestion. I've added the grid solution as well now.

Collapse
 
harshboricha98 profile image
Harsh boricha • Edited

Hey, Thank you for your suggestion. I've added the grid solution as well now.

Collapse
 
imiahazel profile image
Imia Hazel

Thanks for the ideas.

Collapse
 
nmarkovic98 profile image
Nikola Marković

What if the left div have no content inside, how to keep him stretch to the very bottom when scroll?

Collapse
 
harshboricha98 profile image
Harsh boricha

It is still stretched if there is no content inside.
can you elaborate more on this?