Reputation: 573
Let's say I have a container, and that I want to put this one container into yet another container that's also full of other stuff. The CSS code might look something like this:
.parent-container {
width: 100%;
position: relative;
}
.child-container {
width: 600px;
position: absolute;
left: 25px;
bottom: 100px;
}
However, .child-container
also includes absolutely positioned elements, which are position relatively to .parent-container
because .child-container
doesn't have position: relative
. So my question is, how can I position .child-container
's children relatively to itself, while still keeping it correctly positioned in .parent-container
?
P. S. Wrapping .child-container
in a position: absolute
'd div
and making .child-container
position: relative
should do the trick, but I was hoping for something more... semantic.
Upvotes: 1
Views: 129
Reputation: 30107
Absolutely positioned elements should already be relative to their parent. Here's a demo which shows nested items within absolute positioning
HTML
<div class='parent-container'>
Parent
<div class='child-container'>
1st Child
<div class='grandchild-container'>
2nd Child
</div>
</div>
</div>
CSS (color added to illustrate differences)
.parent-container {
position: relative;
background: grey;
}
.child-container {
position: absolute;
background: red;
left: 20px;
}
.grandchild-container {
position: absolute;
background: yellow;
left: 20px;
}
It will look like this
*Notice each position is relative to its parent.
For more info see:
Upvotes: 0
Reputation: 943996
However, .child-container also includes absolutely positioned elements, which are position relatively to .parent-container because .child-container doesn't have position: relative.
Incorrect. Absolute positioning is with respect to the nearest ancestor that is positioned, not position: relative
. Anything except position: static
will make an element positioned. (position: relative
won't move the container out of normal flow so it is used when you want to set a positioning context with no side effects).
Since the parent is position: absolute;
they are positioned with respect to that already.
Upvotes: 4
Reputation: 2818
You don't need to change .child-container position to relative in order to set him has "relative" parent. please review this link from MDN about position absolute.
"The absolutely positioned element is positioned relative to nearest positioned ancestor. If a positioned ancestor doesn't exist, the initial container is used."
*positioned ancestor is an element with either: relative, fixed or absolute position
Upvotes: 2