Explain Codes LogoExplain Codes Logo

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

html
responsive
scrolling
accessibility
Anton ShumikhinbyAnton Shumikhin·Aug 11, 2024
TLDR

To make a fixed element scrollable when the content overflows, use overflow-y: auto; in conjunction with max-height: 100vh; This will keep the element within the viewport, adding a scrollbar when needed.

.fixed-element { position: fixed; // Stay right where you are! max-height: 100vh; // Don't grow bigger than the viewport, I mean it! overflow-y: auto; // Reach for the scrollbar if you must! }
<div class="fixed-element"> <!-- Overflowing content, like too much champagne in a glass! --> </div>

Keep your styles clear and crisp. This avoids bloating and ensures easy maintainability.

Adding spice with styling

Getting sassy with responsiveness

To make your fixed element go with the flow (responsive), grasp percentage values or viewport units (vh, vw). Media queries will bend the styles to your will across different devices.

@media (max-width: 600px) { // talking to mobiles & tablets here .fixed-element { max-height: 50vh; // Slice down to half for a slim look } }

Smooth operator for mobile experience

For velvet scrolling on touch devices, whisper -webkit-overflow-scrolling: touch; to your fixed element.

.fixed-element { -webkit-overflow-scrolling: touch; // Scroll like you're on butter }

Settling the fight between style and structure

Chop up your HTML and CSS, segregating the soldier styles from the civilian content styles. Give your scrollable area a shiny medal (border) for distinction.

.fixed-element { border: 1px solid #ccc; // Border, standing proud and tall }

Let the inner content hold the torch high (height: 100%;) to keep the scrolling in check:

<div class="fixed-element"> <div class="inner-content" style="height: 100%;"> <!-- Scrollable content, like the credits at the end of a movie --> </div> </div>

Royal decree for JavaScript

Call upon your JavaScript knights to dynamically adjust the max-height of the fixed element and to command the scrollability based on the size of the content and the ever-fluctuating viewport. Be on the lookout for resize events and gauge the overflow status.

window.addEventListener('resize', function() { // I'm all ears for resizing var fixedElement = document.querySelector('.fixed-element'); // Our target, locked var isContentOverflowing = fixedElement.scrollHeight > fixedElement.clientHeight; // Wait, are we spilling out? fixedElement.style.overflowY = isContentOverflowing ? 'auto' : 'hidden'; // Makes scrollbar appear/disappear like a magic trick });

Championing accessibility

Test the waters with keyboard navigation and sprinkle some ARIA pixie dust for accessibility. Mark the trail for interactivity with clear visual cues.