Scrolling divs are a ubiquitous feature on modern websites. By restricting and customizing scroll behavior to key content sections, we can enhance usability for long pages. With some CSS and JavaScript code, we can build customizable scrollable divs tailored to our sites‘ designs and interactions.
Why Use Scrollable Divs?
Here are some of the key benefits of using scrollable div elements:
-
Fit more content – A scrollable div can contain long form text, images, widgets etc. without breaking layout or overflowing the parent container. This helps fit more content in available space.
-
Focus user attention – Scrolling applies focus to a section by keeping relevant content visible at all times while browsing. This draws user gaze and is useful for highlight components like testimonials.
-
Enhanced performance – Restricting scroll areas avoids inefficient rendering and repaints outside of the viewport that hurt smoothness on long pages. Targeted divs optimize scroll paint areas.
-
Add scroll effects and animations – Custom JavaScript handled scrolling opens possibilities like snap points, parallax effects and inertia that aren‘t possible with native browser scrolling.
-
Responsive sizing – Scrollable divs can intelligently adapt their maximum heights and behaviors to different viewport sizes using CSS media queries.
According to web performance surveys by Cloudinary, sites utilizing targeted scroll containers have over 50% faster hero render times compared to excessive full page scrolling. Clearly optimizing scroll regions can tangibly reduce jank and lag for users.
HTML Structure for Scrollable Divs
The HTML foundation for a scrollable div is simple:
<div class="scrollable">
<div class="content">
<!-- Content Goes Here -->
</div>
</div>
The outer <div> container has a .scrollable class for styling and behavior. Inside of it we place a .content container for our scrollable content.
This keeps things reusable – any widgets can be placed in .content and wrapped with a .scrollable shell for customized scrolling.
Style the Scroll Container
First, some initial CSS for sizing and appearance:
.scrollable {
max-height: 360px;
overflow: auto;
background: #f3f8fa;
padding: 12px;
}
.content {
height: 100%;
}
The key property is overflow: auto – this establishes the .scrollable div as a scroll container by not clipping overflowing child content.
Height can be any fixed value or percentage you want to constraint – here we use 360px. Width can stretch 100% without overflow.
The .content div fills 100% height so children that exceed this will activate scrolling functionality.
Populate Scroll Content
With structure and styles set up, we can now populate our scrollable component with some example content:
<div class="scrollable">
<div class="content">
<h2>Section Heading</h2>
<p>Lorem ipsum dolor sit amet...</p>
<p>Consectetur adipiscing elit...</p>
</div>
</div>
This can be any HTML – images, lists, iframes etc. As long as content overflows 360px height, scrolling will engage.
Flexbox Content Centering
A nice enhancement is horizontally and vertically centering scroll content using Flexbox:
.scrollable {
display: flex;
align-items: center;
justify-content: center;
}
Activated with display: flex, the align and justify properties keep content centered during scrolling.

This applies regardless of scrolling, keeping content neatly framed.
Customize Scrollbar in CSS
The browser‘s native scrollbar may not match site style or brand colors. Luckily we can heavily customize the scrollbar appearance with CSS.
The relevant pseudo-elements are -webkit-scrollbar and -webkit-scrollbar-thumb for WebKit browsers:
.scrollable {
scrollbar-color: #3876ac #f4f4f4;
scrollbar-width: thin;
}
.scrollable::-webkit-scrollbar {
width: 12px;
}
.scrollable::-webkit-scrollbar-track {
background: #f3f8fa;
}
.scrollable::-webkit-scrollbar-thumb {
background: #3876ac;
border-radius: 100px;
border: 3px solid #f4f4f4;
}
This example adds color, rounded corners, width and other styling to the scrollbar internals.
Cross browser support is limited but still improves the experience on most modern browsers including Chrome, Safari and Edge.
JavaScript Powered Scrolling
For more control and added behavior beyond native scrolling, we can enable scrolling through JavaScript instead of CSS overflow.
Setup Scroll Tracking
First we need elements references and scroll position tracking variables:
// Element References
const scrollable = document.querySelector(‘.scrollable‘);
const content = document.querySelector(‘.content‘);
// Scroll State
let scrollY = 0; //pixels scrolled from top
let scrollHeight = content.offsetHeight; //full scroll height
Scroll Event Handlers
On wheel and touch events we call our scroll handler:
scrollable.addEventListener(‘wheel‘, handleScroll);
function handleScroll(event) {
// Scroll Logic
}
Touch events use similar with a handleTouch listener function.
Calculate Scroll Position
In the handler, we get the wheel pixel delta for direction and distance scrolled:
let deltaY = event.deltaY * 20; //scale speed
scrollY = Math.max(0, Math.min(scrollY - deltaY, scrollHeight));
Then update our position relative to the delta, keeping within bounds.
Finally apply to the content element:
content.style.transform = `translateY(-${scrollY}px)`
This powers smooth performer JavaScript scrolling!
Inertial Scrolling
We can also add inertial scrolling for momentum if the user quickly flicks:
let inertia = 0;
function handleScroll() {
inertia = scrollY - prevY;
//Gradually decrease towards 0
}
function update() {
scrollY += inertia;
inertia *= 0.95;
}
This accumulates velocity from previous positions and gradually slows scrolling down, like native app scrolling.
FEATURES AND CUSTOMIZATIONS
With our scroll foundation built, what are some features we can add?
Scroll Progress Indicators
A scrollbar or line showing scroll progress is useful user feedback:
<span class="indicator"></span>
We position based on the current ratio:
let ratio = scrollY / scrollHeight;
indicator.style.transform = `scaleY(${ratio})`;
Spruce up with gradients, slots and animations!
Scroll Snapping
For content broken into visual sections, we can apply scroll snap points:
.scrollable {
scroll-snap-type: y mandatory;
}
.content > div {
scroll-snap-align: start;
}
This hardware accelerates scrolling performance and satisfyingly snaps between child divs.
Parallax Scrolling
Parallax creates perspective illusions as different layers move at different scroll speeds:
<div class="parallax-bg">
</div>
<div class="content">
</div>
We offset layers using different position ratios:
// Parallax ratio factor
let parallax = 0.8;
bg.style.transform = `translateY(-${scrollY * parallax}px)`;
fg.style.transform = `translateY(-${scrollY}px)`;
The foreground scrolls faster than the background, creating depth and immersion.
Accessibility Considerations
When using custom scroll implementations, we need to ensure accessibility best practices are followed:
- Use proper semantic markup like
<main>,<aside>and heading levels. - Add ARIA roles like
role="region"to identify content sections. - Support keyboard navigation and screen readers with items like arrow key event listeners.
- Convey scroll overflow to assistive technology through attributes like
aria-expanded. - Don‘t remove default keyboard scrolling unless it degrades experience for users requiring this.
- Follow color contrast minimums of 4.5:1 for text and background.
- Allow text resize without breaking layout using fluid
remunits. - Support screen magnifiers by avoiding fixed positioned UIs and truncated text.
- Handle text direction changes for right-to-left languages.
Conforming to standards and guidelines ensures that custom scroll implementations don‘t inhibit usage for those relying on assistive tools.
Alternative Approaches
While restricted scrollable divs serve well for concentrate blocks of related content, some alternative scrolling patterns include:
Full Page Scrolling
Here the entire view scaffolds unique full bleed sections:
<div id="section1" class="section">
</div>
<div id="section2" class="section">
</div>
Pros:
- Visually engaging hero scenes.
- Link navigation between sections.
Cons:
- Performance heavy.
- Interferes with site navigation.
Position Sticky Sidebars
Menus and side content lock while main column scrolls:
<aside>
<div class="sticky">
</div>
</aside>
<main>
<div class="content">
</div>
</main>
Pros:
- Persistent navigation access.
- Less resource intensive.
Cons:
- Mobile layout limitations.
- Potentially distracting fixed overlays.
There are many other patterns possible like endless scrolling, hero images and anchored jump links. Choose what best matches design goals and user journeys!
Conclusion
Scrollable content divs enable us to build performant, focused scrolling for long form layouts. Customizing scroll behavior opens creative doors for innovations like snapping, parallax and infinite feeds.
Some key pointers in review:
- Overflow containers restrict paints to visible areas.
- Flexbox enables convenient content alignment.
- JavaScript handles smoothness and interactivity.
- Accessibility standards must remain front of mind.
- Many options exist beyond basic div components.
While largely self-contained, these scroll boxes can integrate with navigation menus, on page links and other features for intuitive workflows. When applied judiciously, scrolling unlock immersive user experiences otherwise unattainable on wide static pages.


