Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the css property top calculated for absolute elements that do not set the property themselves? [duplicate]

Tags:

html

css

Possible Duplicate:
position: absolute without setting top/left/bottom/right?

Looking at the following code, I have div#box2 that has position: absolute set on it. It is in between two divs that have position: static set on them. Based on the following code, I would expect div#box2 to be at the top left of the body element. However, when it is rendered it receives a top value placing it beneath box1. Why does this happen?

I understand that when I explicitly set the top value of div#box2 to 0px, it appears at the top. I just don't know why it is not computed to 0px by the browser to begin with.

Here is some sample code:

<!DOCTYPE html>
<html>
  <head>
    <title>Position Test</title>
    <style type="text/css">
      body { background-color: #DEDEDE; }
      #content { border: solid; }
      #content div { height: 150px; opacity: .7;}
      #box1 { background-color: red; }
      #box2 { background-color: yellow; }
      #box3 { background-color: lightblue; }

    #content div { width: 150px; }
        #box2 { position: absolute; text-align: right;}
    </style>
  </head>
  <body>
    <div id="content">
      <div id="box1"><span>1</span></div>
      <div id="box2"><span>2</span></div>
      <div id="box3"><span>3</span></div>
    </div>
  </body>
</html>
like image 317
blinkmacalahan Avatar asked Dec 11 '25 12:12

blinkmacalahan


1 Answers

The default value of top is "auto", not "0" (source), therefore it should not be positioned at the top of the <body> element.

As for why "auto" translates to "same position as if position was static", see the CSS specification on positioning (emphasis mine):

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’: First set any ‘auto’ values for ‘margin-top’ and ‘margin-bottom’ to ‘0’, then set ‘top’ to the static position, and finally apply rule number three below.

...

like image 79
0b10011 Avatar answered Dec 14 '25 05:12

0b10011