我有两行数据(绿色)和一个标题(红色),它应始终可见:
看看我已有的例子:
http://jsfiddle.net/j9C8R/33/
这是我目前的HTML:
<div class="main">
<div class="row">
<div class="sticky">Sticky header A</div>
<div class="content">ContentA</div>
<div class="content">ContentA</div>
<div class="content">ContentA</div>
<div class="content">ContentA</div>
</div>
<div class="row">
<div class="sticky">Sticky header B</div>
<div class="content">ContentB</div>
<div class="content">ContentB</div>
<div class="content">ContentB</div>
<div class="content">ContentB</div>
</div>
<div class="row">
<div class="sticky">Sticky header C</div>
<div class="content">ContentC</div>
<div class="content">ContentC</div>
<div class="content">ContentC</div>
<div class="content">ContentC</div>
</div>
<div class="row">
<div class="sticky">Sticky header D</div>
<div class="content">ContentD</div>
<div class="content">ContentD</div>
<div class="content">ContentD</div>
<div class="content">ContentD</div>
</div>
<div class="row">
<div class="sticky">Sticky header E</div>
<div class="content">ContentE</div>
<div class="content">ContentE</div>
<div class="content">ContentE</div>
<div class="content">ContentE</div>
</div>
</div>
和CSS:
.main {
background-color:blue;
overflow:scroll;
height:200px;
width:400px;
}
.row {
height:50px;
overflow:scroll;
clear:both;
width:1000px;
background-color:yellow;
}
.sticky,.content {
float:left;
width:150px;
border:1px solid black;
}
.sticky {
background-color:red;
}
.content {
background-color:green;
}
现在红色标题与内容一起滚动,但它应该粘贴到现在的位置,但是与内容垂直滚动(MS Excel样式).
如何实现(最好只使用CSS).
更新:重要的是红色标题与相应的内容一起垂直滚动,但在水平滚动时会粘在左边缘.
解决方法
我不认为有可能通过纯css实现你的目标,因为粘性的项通常使用position:fixed,不幸的是它相对于视口修复了它们.
使用javascript(在这种情况下是jquery库)和绝对定位,你应该能够实现你的目标:
新款式:
.row {
height:50px;
overflow:scroll;
clear:both;
width:1000px;
position:relative; //for the absolute positioning of sticky
background-color:yellow;
padding-left:150px; //this is the size of your sticky column so it doesn't cover content when fully left
Box-sizing:border-Box;//this is so the padding doesn't add extra width to your 1000px
}
.sticky {
background-color:red;
position:absolute; left:0; top:0;
}
JavaScript的:
$('.main').scroll(function() {
$(this).find('.sticky').css('left',$(this).scrollLeft());
});
http://jsfiddle.net/j9C8R/36/