CSS: Absolute Element inside Absolute Element [dup

2019-09-06 22:42发布

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 :)

1条回答
你好瞎i
2楼-- · 2019-09-06 23:27

Positioning an absolute element in relation to an absolute parent is "absolutely" the same as with a relative parent. In fact it's also the same if the parent were fixed.

Basically you will always position an absolute element in relation with the closest parent with NO position:static (which is the position of all elements by default).

While learning the example most common is absolute inside relative because while you are making some basic html, the first element you need to be absolute won't be positioned (probably) as you wish till you set relative to the parent and that won't change the position of this parent at all (from static to relative 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 adding position:relative to so many classes?". Yes, I coudn't understand it either till some day I needed an absolute element to be positioned in relation to NOT the closest parent. (for example, a position of an absolute submenu on relation to the main-menu ul but not to his direct parent which would be a li). Hope it's clear enough

查看更多
登录 后发表回答