Home > Net >  How to scroll to a div's all edges when zoomed
How to scroll to a div's all edges when zoomed

Time:08-25

Using CSS alone, I am trying to perform a panning behavior on a div that's positioned absolute inside a parent div.

I ultimately want to change the width and height dynamically (zoom in and out behavior). I want to be able to pan (using scrolling) across the whole child div when the size is bigger than the parent.

The child div has bigger width and I expect to scroll to see all 4 edges of it. But, the scroll only happens to the right side and the bottom side. If I have some content in that div – which would be rendered in the top left corner of the div – I can't scroll to it.

.container {
  height: 300px;
  background: red;
  position: relative;
  overflow: scroll;
}

.child {
  font: 400 14px/17px 'Roboto';
  color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 200%;
  width: 200%;
  background: black;
  opacity: .5;
}
<div >
  <div >
    Demo Text To Be Shown
  </div>
</div>

enter image description here

In this example, the child div has 200% in width and height. I can't scroll to see the left and top edges.

CodePudding user response:

It's just not possible for an element to scroll further up than the top. Here's what you can do instead: give the container some padding so the child isn't off-screen.

.container {
      height: 300px;
      padding-top: 150px;
      padding-left: 50%;
      background: red;
      position: relative;
      overflow: scroll;
    }
    
    .child {
      position: absolute;
      top: 0;
      left: 0;
      height: 200%;
      width: 200%;
      background: black;
      opacity: .5;
      color: grey;
    }
<div >
  <div >
    Demo Text To Be Shown
  </div>
</div>

CodePudding user response:

I'm not sure What you want to achieve. I presume you want to see the text:

I amend a bit your CSS:

.container {
 height: 300px;
 background: red;
 position: relative;
 overflow: scroll;

}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-25%, -25%);
  height: 200%;
  width: 200%; 
  background: black;
  opacity: .5;
  color:red;
 }

I change transform from -50 to -25 and add color:red. Text appears in the left top corner.

  • Related