Search code examples
csspositioningabsolute

CSS: placing absolute positioned element so that it touches its parent from outside


I want the absolute positioned child touch its parent from outside like this:

.parent {
  background: #aaffaa;
  width: 200px;
  height: 200px;
  margin-left: 150px;
  display: flex;
  align-items: center;
  position: relative;
}

.child {
  background: #ffaaaa;
  width: 100px; // actually unknown, here for demo purposes
  height: 100px;
  position: absolute;
  left: 0;
  transform: translate(-100%);
}
<div class="parent">
  <div class="child"></div>
</div>

The problem: I can't use the transform property, because it's already in use in a keyframe animation, the element may or may not be position: absolute. Is there some elegant solution to this?


Solution

  • Sure there is! There is just 1 line missing in your code. You just need to use right:100% and it will be just fine.

    .parent {
      background: #aaffaa;
      width: 200px;
      height: 200px;
      margin-left: 150px;
      display: flex;
      align-items: center;
      position: relative;
    }
    
    .child {
      background: #ffaaaa;
      width: 100px;
      height: 100px;
      position: absolute;
      right: 100%;
    }
     <div class="parent">
            <div class="child"></div>
          </div>