Question

Just like the title, why div (or p or any other elements in html) have 'position: static' as the default value? Why not 'position: relative'? I don't see any benefit using 'position: static' in my css. Is it safe to define all div elements in html using 'position: relative'?

EDIT: I'm quite aware the difference between static, relative, absolute, and fixed positioning. But the main problem is why the default positioning for div or any other html elements is static? This example:

HTML

<div class="div1">
    <div class="div2">
        <div class="div3">
            <div class="div-last"></div>
        </div>
    </div>
</div>

CSS

.div1 {
    width: 700px;
    height: 700px;
    background-color: #000;
    position: relative;
}
.div2 {
    width: 600px;
    height: 600px;
    background-color: #333;
    position: relative;
    top: 20px;
    left: 20px;
}
.div3 {
    width: 500px;
    height: 500px;
    background-color: #777;
    position: absolute;
    right: 0;
    top: 30px;
}
.div-last {
    width: 400px;
    height: 400px;
    background-color: #AAA;
    position: absolute;
    bottom: 20px;
    left: 20px;
}

shows that I don't need a single static positioning to arrange my divs as I want. Here's a jsfiddle of the code above. And sorry for my potato English. :D

EDIT #2: The answer from the related question is: "Yes, it is. If you try to position one element absolute it is positioned relatively to the closest ancestor, which has a CSS position other than static.

If every element has position:relative, this would be the direct parent.

But you might want to position the absolute element relatively to an element further up in the DOM tree or maybe absolutely on the page body."

So, I don't want/need to "position the absolute element relatively to an element further up in the DOM tree or maybe absolutely on the page body.", is there any other technical precautions that I need to know before I make all divs relative?

Was it helpful?

Solution

If position: relative was the default value, position: absolute; would no longer work as expected. That is, because position: absolute uses the closest non-static positioned element in the hierarchy as the reference. If there were no static positioned elements, all would be non-static, so position: absolute would use the parent element as the reference, and thus no longer positioning absolute, but relative to the parent element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top