DEV Community

Cover image for How to Set Element Position to another Element's position.
Mafee7
Mafee7

Posted on • Updated on

How to Set Element Position to another Element's position.

How to Set Element Position to another Element's position. 😎

Did you ever want to set an element's position to another element's position?

You Can Do This Now.

Example:

HTML:

<div id="Elem1">πŸ˜€</div>
<div id="Elem2">πŸ•Ά</div>

<div id="btn">
    Wear Sun Glasses
</div>
Enter fullscreen mode Exit fullscreen mode

Css:

body{
    font-size: 30vh;
    user-select: none;
}
#btn{
    position: absolute;
    top: 2.5vh;
    font-size: 5vh;
    filter: brightness(100%);
    font-family: sans-serif;
    padding: 1vh;
    background: rgb(200,200,200);
    cursor: pointer;
    width: 40vw;
    text-align: center;
}
#btn:hover{

    filter: brightness(80%);
}
#Elem1{
    position: absolute;
    right: 1vw;
}
#Elem2{
    position: absolute;
    z-index: 3;
}
Enter fullscreen mode Exit fullscreen mode

Javascript [OP]:

var btn = document.querySelector("#btn");
var e1 = document.querySelector("#Elem1");
var e2 = document.querySelector("#Elem2");

btn.addEventListener("click", function(){
    e2.style.left = e1.getBoundingClientRect().left + 20 + "px"; // With Offset Of 20px for correct postition
    e2.style.top = e1.getBoundingClientRect().top + "px"; 
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)