如何为不自行设置属性的绝对元素计算css属性?

bli*_*han 3 html css

可能重复:
位置:绝对没有设置顶部/左侧/底部/右侧?

看下面的代码,我有div#box2,它的位置是:绝对设置.它位于两个具有位置的div之间:静态设置在它们上面.基于以下代码,我希望div#box2位于body元素的左上角.但是,当它被渲染时,它会收到一个顶部值,将其放在box1下面.为什么会这样?

据我所知,当我明确地将div#box2的顶值设置为0px时,它会显示在顶部.我只是不知道为什么它不是由浏览器计算到0px开始.

以下是一些示例代码:

<!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>
Run Code Online (Sandbox Code Playgroud)

0b1*_*011 5

的默认值top是" 自动 ",而不是"0"(源),因此它不应该被定位在顶部<body>元件.

至于为什么 "自动"转换为"相同的位置,如果position是static",请参阅关于定位的CSS规范(强调我的):

对于绝对定位的元素,垂直维度的使用值必须满足此约束:

'top'+'margin-top'+'border-top-width'+'padding-top'+'height'+'padding-bottom'+'border-bottom-width'+'margin-bottom'+'bottom '=包含块的高度

如果'top','height'和'bottom'都是'auto',则首先将'margin-top'和'margin-bottom'的'auto'值设置为'0',然后设置'top'到静态位置,最后应用下面的规则三.

...