我有一个标题,我想在垂直和水平滚动期间粘性。我希望它是粘性的,因为头部的高度是动态的(否则,如果我没有弄错,我可以使用fixed )。
我玩了一把小提琴,但没有成功:
https://jsfiddle.net/Viktor/39v0gzjh/22/
CSS:
html, body{
width:100%;
background-color:red;
opacity:0.9;
padding:0;
margin:0;
}
.header{
position:sticky;
top:0;
left:0;
background-color:gray;
height: 100px;
padding:0;
}
.container{
display: flex;
}
.child{
width: 120px;
min-width: 120px;
max-width: 120px;
border: 1px solid #D8D8D8;
background-color: white;
font-weight: bold;
word-wrap: break-word;
}
.bigdiv{
width:1000px;
height:1000px;
}HTML:
<div class="header">
This is my sticky header
</div>
<div class="container">
<div class="child">
child1
</div>
<div class="child">
child2
</div>
<div class="child">
child3
</div>
<div class="child">
child4
</div>
<div class="child">
child5
</div>
<div class="child">
child6
</div>
<div class="child">
child7
</div>
<div class="child">
child8
</div>
<div class="child">
child9
</div>
<div class="child">
child
</div>
</div>
<div class="bigdiv">
Very long div
</div>发布于 2019-06-12 20:33:05
如果您正在使用bootstrap,只需将fixed-top类添加到您的header中
<div class="header fixed-top">
This is my sticky header
</div>否则,在css中,页眉位置应该是"position:fixed;",它的宽度应该是"width: 100%;",然后将其他页面内容放在下面,就像这样:
发布于 2019-06-12 20:47:37
position: sticky运行得很好。您看不到它的效果的原因是因为应用于div的position (而不是可见文本)和div的宽度,它占用了其父100%的div,在本例中是body。
所以当你水平滚动时,你仍然在div里面,它占据了整个可用的宽度空间。
现在,如果你想在不考虑滚动的情况下查看div.header中的内容,将它的宽度修改为width: 100vw,它应该可以正常工作。
您可以通过将body的width设置为140%并将.header设置为100vw进行验证
万事如意。干杯!
发布于 2019-06-12 20:50:58
一种更好的方法是在html上设置overflow-x: scroll;。这将解决问题。
请注意,根据规范,粘滞不会在有溢出的元素中工作。This is a known issue
因此,尝试将javascript与position:fixed结合使用。
$(window).scroll(function() {
if( $(this).scrollTop() > 0 ) {
$('.header').addClass('sticky');
} else {
$('.header').removeClass('sticky');
}
});html,
body {
width: 100%;
background-color: red;
opacity: 0.9;
padding: 0;
margin: 0;
overflow-x: scroll;
}
.header {
width: 100%;
background-color: gray;
height: 100px;
padding: 0;
}
.sticky {
position:fixed;
top:0;
width: 100%;
left:0;
}
.pt-100{
padding-top: 100px;
}
.container {
display: flex;
}
.child {
width: 120px;
min-width: 120px;
max-width: 120px;
border: 1px solid #D8D8D8;
background-color: white;
font-weight: bold;
word-wrap: break-word;
}
.bigdiv {
width: 1000px;
height: 1000px;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header">
This is my sticky header
</div>
<div class="container">
<div class="child">
child1
</div>
<div class="child">
child2
</div>
<div class="child">
child3
</div>
<div class="child">
child4
</div>
<div class="child">
child5
</div>
<div class="child">
child6
</div>
<div class="child">
child7
</div>
<div class="child">
child8
</div>
<div class="child">
child9
</div>
<div class="child">
child
</div>
</div>
<div class="bigdiv">
Very long div
</div>
https://stackoverflow.com/questions/56562061
复制相似问题