我有
<div id="div1">
any not fixed text
but this div has scrollbar
<div id="div2">
this div is fixed (without scrollbar)
</div>
</div>
我需要将 div2
固定到 div1
,但不固定到主浏览器滚动条。类似于“将 div2 粘贴到 div1”。
div1
有滚动条,这就是我需要修复 div2
的原因。
如果我这样做:
#div1 {
position: absolute;
}
#div1 #div2 {
position: fixed;
}
它将修复 div1
和浏览器的窗口,但我只需要 div1
。
测试示例:
<html>
<head>
<style type="text/css">
#div1 {
border: 1px solid gray;
position: absolute;
height: 200px;
width: 400px;
overflow-y: scroll;
}
#div1 #div2 {
position: fixed;
margin-left: 300px;
}
</style>
</head>
<body>
<br><br><br>
<div id="div1">
<div id="div2">fixed text</div>
<div style="height: 400px;"></div>
</div>
<div style="height: 1400px;"></div>
</body>
</html>
Q1:如何将div2
固定为div
Q2: 在这种情况下如何float: right
div2
到div1
的右边(例子是~ margin-left: 350px;
)
谢谢。
最佳答案
问题是您无法将 div2 固定到 div1,因为固定 div 意味着“保留 div 的顶部,从其最近定位容器的内顶部测量,常量”。 内部顶部是指容器的上部,它会随着用户滚动而上下移动。
解决方案 ( jsfiddle here ) 是将 div1 和 div2 固定到外部容器。这将是您的 CSS:
<style type="text/css">
#container{
border: 1px solid gray;
position: absolute;
height: 200px;
width: 400px;
}
#div1{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
overflow-y: scroll;
}
#div2 {
position: absolute;
right: 14px;
top: 0px;
}
</style>
这是你的 HTML
<br><br><br>
<div id="container">
<div id="div1">
<div style="height: 800px;"></div>
</div>
<div id="div2">fixed text</div>
</div>
<div style="height: 1400px;"></div>
关于jquery - 如何使用滚动条将 div 固定到另一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13793433/