skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.

    .parent1 {
      width: 500px;
      height: 50px;
      border: 1px solid;
      position: relative;
    }
    
    .child1 {
      width: 200px;
      height: 100%;
      background-color: blueviolet;
      position: absolute;
      left: 50%;
    }
    
    .parent2 {
      width: 500px;
      height: 50px;
      border: 1px solid;
      position: relative;
    }
    
    .child2 {
      width: 200px;
      height: 100%;
      background-color: blueviolet;
      position: absolute;
      transform: translateX(100%);
    }
    <div class="parent1">
      <div class="child1"></div>
    </div>
    <br>
    <div class="parent2">
      <div class="child2"></div>
    </div>


  2. Remember, if you using percent. With top - left - bottom - right, its according to parent width. But with translate, its according to current element.

    When you make element to left 50%, your left edge stay at 50% not your center element. So all we need is push there center to this position with translateX(-50%). This is also the popular way to make element center (top, left: 50%, translate(-50%, -50%)

    #parent {
      width: 500px;
      height: 100px;
      border: 1px solid;
      position: relative;
    }
    
    #child {
      width: 200px;
      height: 100%;
      background-color: blueviolet;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
    }
    <div id="parent">
      <div id="child"></div>
    </div>
    <br>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search