I have been working on something where I wanted to move (and animate later) the position of an element based on its own width and I wanted to use pure CSS with it. I have tried multiple things but couldn’t figure out the solution.
I initially, tried using left: 50%
, but the percentage here is according to the parent.
Then I had to rely on JavaScript. I was able to figure it out using JavaScript (below code). But I would like to do this without JS
const child = document.getElementById("child");
child.style.left = child.offsetWidth + "px"
#parent {
width: 500px;
height: 100px;
border: 1px solid;
position: relative;
}
#child {
width: 200px;
height: 100%;
background-color: blueviolet;
position: absolute;
left: 50%;
}
<div id="parent">
<div id="child"></div>
</div>
<br>
2
Answers
After a lot of research, I found that I can use CSS
transform: translateX(100%)
to move the position of an element based on its own width.Remember, if you using percent. With
top - left - bottom - right
, its according to parent width. But withtranslate
, its according to current element.When you make element to
left 50%
, your left edge stay at50%
not your center element. So all we need is push there center to this position withtranslateX(-50%)
. This is also the popular way to make element center(top, left: 50%, translate(-50%, -50%)