I have the following code. I am confused why at left: 100%
the absolute
position inner div sits outside the relative
containing div
.
If anyone can explain why and ideally the fix would mean it would remain within the red outer div
<div
style={{
position: "relative",
backgroundColor: "red",
width: "100%",
height: 100,
}}
>
<div
style={{
borderRadius: 10,
backgroundColor: "green",
height: 20,
width: 20,
position: "absolute",
left: "100%"
}}
/>
</div>
3
Answers
The reason of sitting outside of parent div is child div has absolute position and left:100% css property now. In css, left:100% means 100% of the relative div’s width when child div’s position property set as absolute. So if you want to set the child div inside the parent div, you have to set left property less than 100%-child’s width.
https://www.w3schools.com/css/css_positioning.asp
please check this link for more detail.
The reason your green div went outside of it’s parent border is because it’s positioned absolute in relative to the red div which is it’s parent and it’s nearest positioned ancestor (i.e., the nearest ancestor that is not static)
and it has the CSS property
left: "100%"
which moves it 100% to the left of it’s parent and puts it right outside of it’s border.to stop the green div from going outside it’s parent you can do one of these two:
transform: translateX(-100%)
right: 0
instead ofleft: 100%
Problem
You have two
<div>
elements, the inner one and the outer one. I believe the issue is because the inner<div>
element hasposition: absolute;
. Citing from MDN:The closest positioned ancestor here is the outer
<div>
element which has theposition: relative;
.The combination of
position: absolute;
andleft: 100%;
takes the inner<div>
out of the normal document flow and positions it to the right by a distance equal to100%
of the width of its closest positioned ancestor, which is the outer<div>
.This causes the inner
<div>
to overflow to the right and be completely outside the visible area of its parent container, making it appear as if it’s sitting outside the container.Problem
Solution
The solution would be to adjust the positioning of the inner
<div>
by subtracting its own width from the full width of its containing outer<div>
.In this case, it’ll be:
Solution
Also, see: Why does setting the
right
CSS attribute push an element to the left?