CSS:将固定位置(position fixed)转换为绝对位置(position absolute)。

5 浏览
0 Comments

CSS:将固定位置(position fixed)转换为绝对位置(position absolute)。

我想将一个固定位置的div放到一个绝对位置的div中。我的代码不起作用,所以我该如何使div .box 成为固定的?\n

.container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  height: 90%;
  border: 1px solid black;
  overflow-y: auto;
}
.box {
  position: fixed;
  height: 50px;
  width: 90%;
  top: 0;
  left: 50%;
  transform: translate(-50%);
  border: 1px solid black;
}

\n

  这个固定位置的div没有保持固定
  文本
  文本
  文本
  文本
  文本
  文本
  文本
  文本
  文本
  文本
  文本
  文本
  文本
  文本
  文本
  文本
  文本
  文本

0
0 Comments

这个问题的出现原因是因为使用了CSS的position属性将.box元素设置为sticky,这会使得它相对于滚动容器(.container)固定在页面上方。然而,由于它的父元素(.container)的position属性被设置为absolute,.box元素的固定定位将无效。

要解决这个问题,可以将.box元素的position属性从sticky改为fixed。这样,.box元素将相对于整个文档窗口进行固定定位,而不是相对于滚动容器进行固定定位。修改后的代码如下:

.container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  height: 90%;
  border: 1px solid black;
  overflow-y: auto;
}
.box {
  position: fixed;
  height: 50px;
  width: 90%;
  top: 0;
  border: 1px solid black;
  background-color: white;
}

这样修改后,.box元素将在页面滚动时保持固定位置。

0
0 Comments

问题出现的原因是在CSS中使用了position: fixed,但是该元素无法保持固定位置。解决方法是使用position: absolute代替position: fixed,或者尝试使用position: sticky来实现相同的效果。

以下是修改后的代码示例:

.container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  height: 90%;
  border: 1px solid black;
  overflow-y: auto;
}
.box {
  position: sticky;
  height: 50px;
  width: 100%;
  top: 0;
  border: 1px solid black;
}

This div in fixed position does not stay fixed
Text
Text
Text
Text
Text
Text
Text
Text
Text
Text
Text
Text
Text
Text
Text
Text
Text
Text
Text

请注意,position: sticky在Internet Explorer、Edge 15及之前的版本不被支持。在Safari浏览器中,需要添加-webkit-前缀。同时,为了使sticky定位生效,必须至少指定top、right、bottom或left中的一个属性。

0