固定定位(position: fixed)不将元素基于视口定位。

3

I've read in a number of places that position: fixed; should base the element in the viewport, not it's parent element, because it has been removed from normal document flow. However, as can be seen in the following code it does seem to work this way. The element with position fixed takes it's starting point in the parent element . What gives!? Thanks.

<!DOCTYPE html>
<html>
<link rel="stylesheet" href="cssreset.css">
<head>
<title>TTK</title>
<style>
* {
 box-sizing: border-box; 
}
.container {
 width: 500px;
 height: 500px;
 margin: 25px auto;
 border: 5px solid black;
 position: relative;
 background: yellow;
}
.positionFixed {
 width: 750px;
 height: 250px;
 border: 3px solid blue; /* why does the border not show up */
 position: fixed;
 background: red;
}
</style>
</head>]
<body>
<div class="container">
 <div class="positionFixed"></div>
</div>
</body>
</html>


我不理解CSS注释中的问题,这里有一个可用的jsfiddle。如果您不添加rblarsen答案的方面,positionFixed将固定在左上角。由于positionFixed的宽度更大,它会覆盖容器。 - DomeTune
2个回答

1

1
如果你不指定position:fixed;元素的位置,它就不知道该去哪里。添加一些位置信息(如上、左、右和/或下),它就会被正确地定位。
.positionFixed {
    width: 750px;
    height: 250px;
    border: 3px solid blue; /* why does the border not show up */
    position: fixed;
    top:0;
    left:0;
    background: red;
}

1
感谢您的反馈。如果我不使用任何定位(如top、left等),那么具有position: fixed;属性的元素将使用其父元素而非视口作为定位基准。 - user7532895
如果您不使用任何定位,它将放置在代码中放置的位置,就像它具有position:static;一样。 - razemauze

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接