Preventing child of unknown width overflowing the parent with unknown width

Hello, there is a codepen: https://codepen.io/Ddystopia/pen/PoMbaEX?editors=1100

Please look at it to understand the question better, thank you.

You can see 2 boxes. In first: child overflows the parent. In second: child snaps to the parent (see .hack class and it’s comment).

The question: how to produce the same effect as in second block, but without using var(--child-width) - because in the real use case child’s size is dependent on it’s content.

Additional notes:

  • This is a hard requirement for child to be absolutely positioned with left ∈ [0%; 100%] and top ∈ [0%; 100%] .
  • Both parent’s and child’s width are non deterministic.
  • Instead of left it may be right, instead of top it may be bottom. It is absolutely symmetrical and does not have a difference.
  • Snapping for both x and y axis, but example only show cases x axis with possible overflow on right. It is trivial to construct different showcases, but there is a lot of them.

Code

main {
  --child-width: 30px;
  
  width: 120px;
  height: 80px;
  display: flex;
  flex-wrap: nowrap;
  gap: 10px;

  /* For demonstration purposes */
  animation: 1.5s linear infinite slidein;
  margin-bottom: 5px;

}

.container {
   flex: 1 1 1px;
   height: 100%;
   background-color: magenta;
   position: relative;
}

.float {
    width: max-content;
    height: 30%;
    background-color: green;
    position: absolute;
    top: 0;
    left: 60%;
}

.hack {
    /*
     * This gives correct solution, but in practice we can't have
     * `--child-width` available, as it is dynamic
     * Comment this line out to see the problem.
     */
    left: calc(min(60%, 100% - var(--child-width)));
}

.float > div {
  /* 
   * We can't actually have that number in css
   */
  width: var(--child-width); 
}

.neiborg {
  width: 150px;
  height: 100%;
  background-color: orange;
}

/* For demonstration purposes */
@keyframes slidein {
  0%, 100% {
    width: 200px;
  }
  50% {
    width: 260px;
  }
}
<main>
  <div class="container">
    <div class="float"> <div></div> </div>
  </div>
  <div class="neiborg"> </div>
</main>
<main>
  <div class="container">
    <div class="float hack"> <div></div> </div>
  </div>
  <div class="neiborg"> </div>
</main>

Please Tell us what’s happening in your own words.

Learning to describe problems is hard, but it is an important part of learning how to code.

Also, the more you say, the more we can help!

Hello, I’m not sure what exactly are you requesting :smile:

if you need help, please talk about what kind of help you need

I feel like this question/example is a little too abstract.

Could you please provide the context and an example that is closer to the actual implementation you need it for?