This question already has an answer here:
I'm studying CSS and as I learn, when an absolute element A inside relative element B, that A will be relative to B. I want to test the case absolute element inside absolute element but I don't see any differences.
Here is my test:
<div id="box-1">
<div id="box-2"></div>
</div>
Absolute inside Relative
#box-1 {
width: 200px;
height: 200px;
background: #000000;
position: relative;
}
#box-2 {
width: 100px;
height: 100px;
left: 50px;
top: 50px;
background: #e2e2e2;
position: absolute;
}
Absolute inside Absolute
#box-1 {
width: 200px;
height: 200px;
background: #000000;
position: absolute;
}
#box-2 {
width: 100px;
height: 100px;
left: 50px;
top: 50px;
background: #e2e2e2;
position: absolute;
}
So. my question is: Are there any differences when an absolute element is inside other absolute element ? If not, why every examples that I have read always just mention the case absolute element inside other relative element ?
thanks :)
Positioning an
absolute
element in relation to anabsolute
parent is "absolutely" the same as with arelative
parent. In fact it's also the same if the parent werefixed
.Basically you will always position an
absolute
element in relation with the closest parent with NOposition:static
(which is the position of all elements by default).While learning the example most common is
absolute
insiderelative
because while you are making some basic html, the first element you need to beabsolute
won't be positioned (probably) as you wish till you setrelative
to the parent and that won't change the position of this parent at all (fromstatic
torelative
shoudn't make any difference on any element).Probably your next question you may find willing to do is "why not all the elements are set to
position:relative
by default if it won't change the flow of the html at all and then you save time not addingposition:relative
to so many classes?". Yes, I coudn't understand it either till some day I needed anabsolute
element to be positioned in relation to NOT the closest parent. (for example, a position of anabsolute
submenu on relation to the main-menuul
but not to his direct parent which would be ali
). Hope it's clear enough