user10312286
user10312286

Reputation:

How can I display scroll bars in the left direction too?

I wrote the following code.

This code hoped to display scroll bars on both left and right.

However, in fact you can only scroll to the right.

body {
  overflow: auto;
}

.box1 {
  position: absolute;
  height: 100px;
  width: 100px;
  left: -50px;
  background-color: red;
}

.box2 {
  position: absolute;
  height: 100px;
  width: 100px;
  right: -50px;
  background-color: blue;
}
<div class="box1"></div>
<div class="box2"></div>

thank you.

Upvotes: 2

Views: 50

Answers (1)

j3ff
j3ff

Reputation: 6089

Like other comments said, left overflow is hidden "by design" but...

What you could do is leave the left element at position left: 0; and then position your right element out of the view port with right: -100px; after what you would need to calculate the width of the actual view port and the width of the scrollable area and automatically position the horizontal scrollbar using the formula (scrollWidth - viewWidth) / 2.

You can see the result by running the snippet below.

// get view port width
const viewWidth = document.documentElement.clientWidth;
// get scroll width
const scrollWidth = document.documentElement.scrollWidth;
// position horizontal scroll
document.documentElement.scrollLeft = (scrollWidth - viewWidth) / 2;
body {
  overflow: auto;
}

.box1 {
  position: absolute;
  height: 100px;
  width: 100px;
  left: 0; /* modified value from -50px to 0 */
  background-color: red;
}

.box2 {
  position: absolute;
  height: 100px;
  width: 100px;
  right: -100px; /* modified value from -50px to -100px */
  background-color: blue;
}
<div class="box1"></div>
<div class="box2"></div>

Upvotes: 1

Related Questions