Css定位不按预期工作

时间:2013-06-28 10:12:28

标签: html css positioning

这是我的HTML代码

CSS

       h2
        {
            position: absolute;
            left: 100px;
            top: 150px;
        }
        h1
        {
            position: fixed;
            top: 300px;
        }

HTML

    <h1>
        Heading for Fixed Position
    <h2>
        This is a heading with an absolute position</h2>
    </h1>

我是css的新手所以正在尝试定位。我读了一些

An absolute position element is positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block is <html>:

如果这是正确的,则This is a heading with an absolute position消息必须低于Heading for Fixed Position,因为h1是父对象,而h2是绝对对象必须相对于h1定位。如果我错了,请更正。

这是jsfiddle

http://jsfiddle.net/KXmgG/

2 个答案:

答案 0 :(得分:3)

我想解释一下定位实际上是如何工作的,有4种类型

  • 静态(默认)
  • 相对
  • 绝对
  • 固定

静态位置只不过是文档的正常流程,其中元素在另一个之后呈现(不包括浮点数)

相对位置是一种特殊的东西,当与绝对位置一起使用时,它会变得很强大。如果要使用顶部,左侧,底部和右侧而不是边距,则需要为该元素指定position: relative;,这样,顶部,左侧,右侧和底部属性都可以使用。

当您使用position: absolute;时,它会退出文档流,因此如果您有一个名为div宽度类a的元素。现在,如果您将position: absolute;分配给类a,它将退出文档流程,因此当您使用top: 0;时,它将飞到文档的顶部。因此,为了限制它,我们使用 position: relative;包装容器,这样当您使用position: absolute;时,它将是该特定元素的绝对值,而不是整个文档。< / p>

Demo 1

Demo 2

固定位置完全不同,它也与文档流程中的position: absolute;相同,但区别在于固定定位元素不能相对于任何元素,它与任何元素都没有任何联系,它始终从窗口的顶部,左侧,右侧和底部而不是元素计算,当用户滚动文档时,固定位置元素也会流动。

Demo


来到你的答案,你正在使用固定位置和绝对位置,两者都不在文档流程中,所以它们没有任何关系......

您使用top: 300px;作为固定位置,top:: 150px;表示绝对定位元素,因此固定元素将呈现在绝对元素下方,但是当您尝试滚动时,您的固定元素将滚动到哪里因为position: absolute;元素不会。


评论时编辑

转到w3c验证程序并验证您的文档here

enter image description here

答案 1 :(得分:0)

“绝对位置元素相对于第一个具有静态位置的父元素定位。如果找不到这样的元素,则包含的块为:”

是的,但你没有宣布position:relative

如果你想要父母改造你就是这样的HTML:

<div class="parent">
    <h1 class="child">blabla</h1>
    <h2 class="child">blabla</h2>
</div> <!-- end parent -->

<div class="relative">
    <h1>
        Heading for Fixed Position</h1>
    <h2>
        This is a heading with an absolute position</h2>
</div>

CSS:

.relative{
    position:relative;
    }

JSFIDDLE with

position relative / fixed / absolute /]

http://jsfiddle.net/KXmgG/1/

相关问题