CSS定位绝对无法按预期工作 [英] css positioning absolute not working as expected

查看:84
本文介绍了CSS定位绝对无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am learning CSS and was fiddling with CSS position property. As I understand, the position:absolute will place the element with respect to the browser window and all the elements below will be pushed before the element with position:absolute. But when I run the fiddle, I see that by default the element is placed below the h1 tag and not at the top left corner of the window. Please let me know where I am going wrong in understanding. Below is the code:

<!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>

Plnkr链接-柱塞链接

推荐答案

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

position:absolute positions the element relative to its nearest positioned ancestor element (in this case, its position:relative parent div). Use position:fixed in order to position relative to the window.

这篇关于CSS定位绝对无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆