DEV Community

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

Posted on β€’ Edited on

4

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay