Css – What are the default top, left, botton or right values when position:absolute is used

csscss-position

In a big project, few buttons were misalligned in IE. I found a fix by coincidence, by setting position: absolute without any parameters. It made me wonder, what are the default values of such position? I understand how absolute positioning works and what containing element means. But I don't know where the default values come from. They are definitely not top:0; left:0 which I originally expected.

<!DOCTYPE html>
<html>
<head>
<style>
h1 {
position:absolute;
}
</style>
</head>

<body>
<h1>Absoulute pos</h1>
<p>Paragraph</p>
</body>

</html>

Here is a simple page, and this is how final positioning of the h1 element looks like:

enter image description here

Best Answer

As you suspect, the initial values for all these properties is not 0; it is auto. You can find their property definitions in section 9.3.2 of the spec.

When an absolutely positioned box keeps all its offsets auto (i.e. you don't modify them), it doesn't go anywhere. It remains in the static position, which basically means its usual spot in the layout had it not been positioned at all. Section 10 has all the details (it even has entire paragraphs explaining what "static position" means), but you'll want to focus on 10.3.7:

The constraint that determines the used values for these elements is:

'left' + 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' + 'right' = width of containing block

If all three of 'left', 'width', and 'right' are 'auto': First set any 'auto' values for 'margin-left' and 'margin-right' to 0. Then, if the 'direction' property of the element establishing the static-position containing block is 'ltr' set 'left' to the static position and apply rule number three below; otherwise, set 'right' to the static position and apply rule number one below.

[...]

1. 'left' and 'width' are 'auto' and 'right' is not 'auto', then the width is shrink-to-fit. Then solve for 'left'

And 10.6.4:

For absolutely positioned elements, the used values of the vertical dimensions must satisfy this constraint:

'top' + 'margin-top' + 'border-top-width' + 'padding-top' + 'height' + 'padding-bottom' + 'border-bottom-width' + 'margin-bottom' + 'bottom' = height of containing block

If all three of 'top', 'height', and 'bottom' are auto, set 'top' to the static position and apply rule number three below.

[...]

3. 'height' and 'bottom' are 'auto' and 'top' is not 'auto', then the height is based on the content per 10.6.7, set 'auto' values for 'margin-top' and 'margin-bottom' to 0, and solve for 'bottom'

Related Topic