Inner div element scroll via outer scrollbar

2019-02-20 01:57发布

问题:

I have a div element that scrolls vertically; the scrollbar is within the div element itself. I'd like to have the scrollbar outside of the div, similar to how a typical webpage scrollbar is. Scrollbar looks like any other webpage, but when scrolled only scrolls this particular div element.

<div id="outer">
    <div id="inner"> //to be scrolled
        <!-- content -->
    </div>
</div>

Example Fiddle: http://jsfiddle.net/7pgyt/

I'd like the scrollbar to be to the far right, in the red area. The scrollbar scrolls the blue area. Can this be accomplished in just HTML and CSS?

A possible outcome would be as below:

回答1:

Given the following html structure:

<div id="wrapper">
    <div id="top" class="bar"></div>
    <div id="outer">
        <div id="inner"></div>
    </div>
    <div id="bottom" class="bar"></div>
</div>

You can use the following styles:

#wrapper {
    position:relative;
    height:200px;
}

#outer {
    background-color: red;
    overflow-y:auto;
    height: 200px;
}

#inner {
    color: white;
    font-weight: bold;
    margin-left: auto;
    margin-right: auto;
    background-color: blue;
    margin:50px;
    position:relative; z-index:1;
}

.bar {
    height:50px; 
    z-index:2;
    position:absolute; 
    background:red; 
    left:0; 
    right:20px;
}

#bottom {bottom:0;}
#top {top:0; }

Example

Example with psuedo selectors instead of the bar divs



回答2:

You can use the below:

Demo Fiddle

HTML

<body>
    <div id="outer"></div>
    <div id="inner">..content...</div>
</body>

CSS

body {
    position:relative;
    width:100%;
    margin:0;
    padding:0;
}
div {
    box-sizing:border-box;
}
#outer {
    border:50px solid red;
    padding: 50px;
    position:absolute;
    height:200px;
    right:17px;
    left:0;
}
#inner {
    color: white;
    font-weight: bold;
    height: 200px;
    padding:50px;
    margin-left: auto;
    margin-right: auto;
    overflow-y: scroll;
    background-color: blue;
}


标签: html css scroll