DEV Community

Harsh boricha
Harsh boricha

Posted on • Updated on

Scrollable div 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

Discussion (5)

Collapse
lukeshiru profile image
LUKESHIRU

Tip: Take a look at CSS Grid Layout and Flexbox. Since a few yers now that we don't use position: absolute for layouts.

Cheers!

Collapse
harshboricha98 profile image
Harsh boricha Author • Edited on

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

Collapse
ivanjeremic profile image
Ivan Jeremic

CSS Grid with 100vh ๐Ÿ˜‰

Collapse
harshboricha98 profile image
Harsh boricha Author • Edited on

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.