css 定位绝对不能按预期工作

zil*_*anu 1 css css-position

我正在学习 CSS 并且正在摆弄 CSS 位置属性。据我了解,position:absolute将相对于浏览器窗口放置元素,并且下面的所有元素将被推到具有位置:绝对的元素之前。但是当我运行小提琴时,我发现默认情况下该元素放置在h1标签下方,而不是窗口的左上角。请让我知道我的理解哪里出了问题。下面是代码:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>
  <body>
    <h1>Just some text to check the css positioning in the browserJust some text to check the css positioning in the browserJust some text to check the css positioning in the browserJust some text to check the css positioning in the browserJust some text to check the css positioning in the browserJust some text to check the css positioning in the browserJust some text to check the css positioning in the browserJust some text to check the css</h1>
    <div style="position:relative; background-color:green; width:20px;padding:10px;">
      <div style="position:absolute;background-color:red;padding:10px">
        <span>value</span>
      </div>
    </div>    
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

Plnkr 链接 - Plunker 链接

小智 5

position:absolute相对于其最近定位的祖先元素(在本例中为position:relative其父 div)定位该元素。用于position:fixed相对于窗口定位。