使用仅限CSS使内部div固定

11 浏览
0 Comments

使用仅限CSS使内部div固定

我正在尝试使内部div相对于其父div固定。我在jsfiddle上做了一个代码示例。问题是当你滚动div时,它不再在原来的位置上。我的HTML代码如下:\n

 
     Lorem ipsum dolor

\n和CSS代码:\n

    
.outer{
  position: relative;
  width: 400px;
  height: 300px;
  border: 1px solid black;
  overflow: auto;
}
.inner1{
  position: absolute;
  width:50px;
  height: auto;
  border: 1px solid blue;
  top: 10px;
  right: 10px;
}
.inner2{
  width: 500px;
  height: 500px;
}

\n有没有办法只使用CSS使inner1相对于outer固定?

0
0 Comments

问题原因:在给定的代码中,header div的position属性设置为absolute,使得它不会随着页面的滚动而固定在容器内部。

解决方法:可以使用CSS的position属性和固定定位来解决这个问题。将header div的position属性设置为fixed,这样它就会相对于浏览器窗口固定在容器内部。

以下是修改后的CSS代码:

.header {
    position: fixed;
    top: 0;
    z-index: 2;
    background-color: pink;
}
.container {
    position: relative;
    width: 200px;
    height: 400px;
    background: gold;
}
.cont_elements {
    overflow-y: scroll;
    height: 100%;
}
.element {
    position: relative;
}

这样修改后,header div就会固定在容器内部,无论页面如何滚动。

0
0 Comments

问题的出现原因:

问题是要将内部的div元素设置为固定定位,但目前的CSS代码并没有实现这个效果。内部div元素的样式设置了position为fixed,但是没有实现固定定位的效果。具体原因是没有正确设置内部div元素的top和right属性。

解决方法:

要解决这个问题,需要正确设置内部div元素的top和right属性。可以通过计算来设置right属性的值,确保内部div元素的右边距离外部div元素的右边界为400px。

解决方法的代码如下:

.inner1 {
    position: fixed;
    width: 50px;
    height: auto;
    border: 1px solid blue;
    top: 10px;
    right: calc(100% - 400px); // 400px is the outer div's width
}

以上代码将会将内部div元素设置为固定定位,并且距离外部div元素的右边界为400px。这样就能够实现内部div元素的固定定位效果。

通过以上的解决方法,可以实现将内部div元素设置为固定定位的效果。

0
0 Comments

试试这个...

 <style>
.outer{
  position: relative;
  width: 400px;
  height: 300px;
  border: 1px solid black;
  overflow: auto;
}
.inner1{
  position: fixed;
  width:50px;
  height: auto;
  border: 1px solid blue;
}
.inner2{
  width: 500px;
  height: 500px;
}
</style>

在这个例子中,有一个外部容器(class为"outer"),它的宽度为400px,高度为300px,并设置了边框和滚动条。内部容器(class为"inner1")的宽度为50px,高度为自动,并设置了边框。还有另一个内部容器(class为"inner2"),它的宽度为500px,高度为500px。

问题是内部容器"inner1"的定位为fixed,但它不会相对于外部容器"outer"进行定位,而是相对于视窗进行定位。这导致内部容器"inner1"随着滚动而移动,而不是固定在外部容器"outer"内。

要解决这个问题,可以使用绝对定位(absolute)代替固定定位(fixed)来实现内部容器"inner1"的固定定位。

修改后的代码如下所示:

 <style>
.outer{
  position: relative;
  width: 400px;
  height: 300px;
  border: 1px solid black;
  overflow: auto;
}
.inner1{
  position: absolute;
  width:50px;
  height: auto;
  border: 1px solid blue;
}
.inner2{
  width: 500px;
  height: 500px;
}
</style>

这样,内部容器"inner1"将相对于外部容器"outer"进行定位,并保持固定位置,不会随着滚动而移动。

通过这种方法,我们可以使用纯CSS来解决将内部div固定在外部div中的问题。

0