Home  >  Article  >  Web Front-end  >  How to Make a Sidebar Scroll Independently Using the Browser's Scrollbar?

How to Make a Sidebar Scroll Independently Using the Browser's Scrollbar?

Barbara Streisand
Barbara StreisandOriginal
2024-11-11 06:53:02831browse

How to Make a Sidebar Scroll Independently Using the  Browser's Scrollbar?

How to Scroll Specific DIV Contents Using the Browser's Scrollbar

Introduction

Many websites, like Gizmodo, have a layout where part of the content scrolls with the browser's main scrollbar while other parts remain fixed. While this may seem complex, it can be achieved entirely through CSS.

Solution

To create this effect, we need to consider several aspects:

  • Horizontal Centering: Ensure the overall layout is horizontally centered within the browser window.
  • Main Content Scrolling: Allow the main content on the left to scroll vertically using the main scrollbar.
  • Fixed Sidebar: Keep the sidebar on the right fixed at the top of the window, except when hovering over it.
  • Scroll Overflow: Enable scrolling for the sidebar when hovered over, allowing it to use its own scrollbar.

Implementation

CSS:

html, body, * {
    padding: 0;
    margin: 0;
}

.wrapper {
    min-width: 500px;
    max-width: 700px;
    margin: 0 auto;
}

#content {
    margin-right: 260px; /* = sidebar width + some white space */
}

#overlay {
    position: fixed;
    top: 0;
    width: 100%;
    height: 100%;
}

#overlay .wrapper {
    height: 100%;
}

#sidebar {
    width: 250px;
    float: right;
    max-height: 100%;
}

#sidebar:hover {
    overflow-y: auto;
}

#sidebar>* {
    max-width: 225px; /* leave some space for vertical scrollbar */
}

Markup:

<div class="wrapper">
    <div>

Explanation:

  • Wrapper: Provides a fixed-width container for both the main content and the sidebar.
  • Content: Defines the main scrollable content.
  • Overlay: Creates a fixed element that covers the entire browser viewport, ensuring the sidebar remains visible even while the main content is scrolled.
  • Sidebar: Positions the sidebar on the right and allows it to scroll only when hovered over.

Preventing Scrolling on Sidebar Hover

If desired, the sidebar can be prevented from initiating scrolling when hovered over by modifying the HTML structure and CSS:

CSS:

#wrapper {
    min-width: unset;
    max-width: unset;
    height: 100%;
}

#content {
    margin-right: 0;
}

#sidebar {
    position: fixed;
    top: 0;
}

Markup:

<div>

The above is the detailed content of How to Make a Sidebar Scroll Independently Using the Browser's Scrollbar?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn