Here 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.
- Please run the snippet
Similar question: how to put css max-left or min-left position to absolute object?
Here is a snippet to illustrate the problem. It is very beneficial for understanding the problem:
section {
--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 width is dynamic
*/
left: calc(min(60%, 100% - var(--child-width)));
}
.float > div {
/*
* We can't actually have that number in css, this is
* for the minimal reproducible example
*/
width: var(--child-width);
}
.neiborg {
width: 150px;
height: 100%;
background-color: orange;
}
/* For demonstration purposes */
@keyframes slidein {
0%, 100% {
width: 200px;
}
50% {
width: 270px;
}
}
<section>
<div class="container">
<div class="float"> <div></div> </div>
</div>
<div class="neiborg"> </div>
</section>
<section>
<div class="container">
<div class="float hack"> <div></div> </div>
</div>
<div class="neiborg"> </div>
</section>
Codepen
1