0

When I get mouse's x and y values both of my elements are sliding. I have already tried position:relativein css and I checked some of stackoverflow articles. Where I had made the mistake ?

 window.addEventListener("mousemove", e =>{
    document.getElementById("x-value").textContent= e.x ;
}
)
html,body{
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;
  align-items: center;

}
p{
  margin:0px 5px;
  padding: 0;
}
span *{
  display: inline;
  position: relative;
  max-width: 20%;
}
div{
  width: 500px;  
  display: flex;
  flex-direction: row;
  justify-content: space-around;

}
  <div>
    <p>X = <span id="x-value"> </span> </p> 
    <p>Y = <span id="y-value"> </span> </p>    
  </div>

2 Answers2

0

Give horizontal padding to div so both x and y are exactly on two edges:

    div {
  padding:0 15%;
  width: 500px;  
  display: flex;
  flex-direction: row;
  justify-content: space-between;  //space only in between of x and y
         }

For better sizing also make all elements of your page have box-sizing:border-box

    * {
  box-sizing: border-box;
}
Erfan
  • 1,725
  • 1
  • 4
  • 12
0

This is happening because the text lengths are changing. Quick way to resolve is to pad the numbers. From https://stackoverflow.com/a/10073788/5818406 — be aware, this method converts to string.

window.addEventListener("mousemove", e =>{
    document.getElementById("x-value").textContent= String(e.x).padStart(4, '0')
    document.getElementById("y-value").textContent= String(e.y).padStart(4, '0')
}
)
html,body{
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;
  align-items: center;

}
p{
  margin:0px 5px;
  padding: 0;
}
span *{
  display: inline;
  position: relative;
  max-width: 20%;
}
div{
  width: 500px;  
  display: flex;
  flex-direction: row;
  justify-content: space-around;

}
<div>
    <p>X = <span id="x-value">0000</span> </p> 
    <p>Y = <span id="y-value">0000</span> </p>    
  </div>
franklylately
  • 1,112
  • 10
  • 12