In the example below I need to nudge ins
by 1px
from right to left
But it is moved by 12px
in one step
What is wrong ?
The starting position should be – absolute – in the horizontal center of parent
$('button').on('click', function(){
var ins = $('#ins');
let x = ins.position().left - 1;
console.log(x);
ins.css('left', x + 'px');
});
.wrap{background:lightblue; display:inline-block; width:50%; position:relative; height:54px;}
.ins{background:orange; position:absolute; width:25px; height:25px; left:50%; transform:translateX(-50%);}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrap'>
<div class='ins' id='ins'></div>
</div>
<br>
<button>CLICK</button>
2
Answers
I recommend using CSS Transform to get this done.
Don’t forget to use
left: 0; right: 0; margin: 0 auto;
to put the orange square at the center of the blue rectangle.ins.position().left
has included the negative X translation as well which explain the 12px difference (.ins has a width of 25px)To achieve 1px nudge, use
ins.css('left')
instead to get the cssleft
value as string (e.g. 170px). Then parse it as integer before minus oneparseInt(ins.css('left'), 10) - 1;
(e.g. 170 – 1)