R3ter
R3ter

Reputation: 57

Fix <div> to middle of viewport in pure Javascript w/ 'position: absolute'

I want to fix a <div> to the middle of the screen using pure JavaScript without using position: fixed due to other app design constraints.


Attempts to Fix Include:

JS:

window.addEventListener('scroll', () => {
  document.getElementById('hide-side').style.top='-'+((document.body.scrollTop)*-10)+"%";
}

HTML:

<div className="side">
  <div id="side" >some container</div>
  <div></div>
</div>

CSS:

 #side {
   position: absolute;
   right: 100%;
   background-color: rgb(255, 0, 0);
   display: inline-block;
   opacity: 1;
 }`

Upvotes: 2

Views: 152

Answers (3)

user2226755
user2226755

Reputation: 13223

Pure JS :

enter image description here

window.addEventListener("onresize", me);

me();

function me() {
    const div = document.getElementById("center");
    div.style.left = (window.innerWidth - div.offsetWidth) / 2 + "px";
    div.style.top = (window.innerHeight - div.offsetHeight) / 2 + "px";
}
#center {
position:fixed;
}
<div id="center">center</div>

<div id="middle"></div>

Upvotes: 0

Dylan Anlezark
Dylan Anlezark

Reputation: 1267

I know you have asked for a javascript solution but I just wanted to bring to your attention that what I think you want to achieve can be done with pure html, css.

I have created this fiddle: https://jsfiddle.net/f0b5myzr/5/ where this line:

transform: translate(-50%, -50%);

does all the hard work for you.

Hope this helped.

Upvotes: 1

Victor
Victor

Reputation: 22198

You have to compute the scroll position and position it absolutely.

This in production is quite hard to get it right, since you have to take into account viewport zoom, and other stuff, like when your "modal" is not directly attached to the body, you will have to compute its offset against the document and position it accordingly.

document.body.onscroll=function(e){
  modal.style.top = `${window.scrollY}px`;
}
body{
  height: 2000px;
  background: url(https://www.designyourway.net/blog/wp-content/uploads/2018/06/Seamless-Space-Pattern-by-J.jpg);
}

#modal{
  position:absolute;
  top: 0px;
  border: 1px solid black;
  background: yellow;
}
<div id="modal">
  Modal
</div>

Upvotes: 1

Related Questions