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>