While relative and absolute positioning can be useful, they have the drawback of taking elements out of the flow which can lead to restrictions in their usage. Recently, I came across one such restriction and I'm interested to see if there is a solution.
To explain further: I have a div that is relatively positioned to its parent. The issue arises when, under certain conditions, this out-of-flow element extends beyond the top element (such as the body) and creates a horizontal scrollbar. See the demo below:
.top-container {
width: 80%;
height: 100px;
margin: auto;
border: dashed 2px red;
}
.container {
width: 80%;
height: 50px;
margin: 25px auto;
border: dotted 1px blue;
position: relative;
}
.absolute {
width: 100%;
background-color: black;
color: white;
position: absolute;
top: 30%;
right: -50%;
}
<div class="top-container">
<div class="container">
<div class="absolute">
absolutely
</div>
</div>
</div>
My question is: is there a way to constrain CSS absolutely positioned elements within or aligned with the borders of .top-container
? A method that functions like max-left/max-right
.
(for example, in my case, repositioning the black div so it stays within the confines of the red dashed line)