joehigh1
joehigh1

Reputation: 193

Central div with margin, and ability to scroll out in all directions (using view width and view height)

So I want to have a central div that is full screen, and to make the width and height of the body 150 vw and vh, with a margin of 50% so when you load the page it holds the div central, but you can scroll up, down, left, right, outside of this central div a little bit.

If you do the div 100vw, 100vh, and then the body 200vw, 200vh, it only enables scrolling to the right and downwards.

This is my understanding of how to get towards what I'm trying to do:

HTML:

<div>
centered and full screen div?
</div>

</body>

CSS:

body{
 width:150vw;
 margin-left:50vw;
 height:150vh;
 margin-top:50vh;
}

div{
 width: 100vw;
 height: 100vh;
 border: solid;
}

JAVA:

window.scrollTo(50 + 'vw', 50 + 'vh');

https://jsfiddle.net/dsLnzyxw/3/

But this doesnt work as the javascript doesn't accept vw in the scrollTo function.. but just to give a better idea of what I'm trying to do.

Also understand I might be going around on crazy route trying to achieve something that could be done quite simple in css?

How do I achieve this?

Thanks !

Upvotes: 0

Views: 301

Answers (1)

65536
65536

Reputation: 116

In order to get units relative to the viewport width and viewport height (vw and vh) you could do simple calculations:

window.scrollTo(0.5 * window.innerWidth, 0.5*window.innerHeight);

which would set the scroll position to 50% of the window width and 50% of the window height. window.innerWidth returns the width of the window, and this is multiplied by 50% to get 50% of the width of the window in pixels. The same goes for height. Setting the scroll position is not possible without JavaScript unfortunately.

Upvotes: 1

Related Questions