0
0

More than 3 years have passed since last update.

CSS/stickyについて知るべき事はそんなに多くない。

Last updated at Posted at 2020-03-06

テーマ

 position:stickyをどれだけ深く掘り下げたところで、落ち着く先のパターンなんか一つや二つ。
 まずは使い方のアイデアを練って、それを可能にする。たったそれだけのお話に必要な知識はせいぜい↓こんなもの。

1. sticky(z-index:2)に妹relative(z-index:1)を作る。

 stickyがうまく機能しない場合、「ブラウザがIEではないか。」→「stickyの後ろ(同じ親)にrelativeやstickyはあるか。」→「z-indexは正しい指定になっているか。」をチェックする。

2. 困った時はfixed(overflow:auto)を併用。

 最前面に配置する要素がtop:0でなく、且つ妹relativeを配置している場合、その妹は兄貴の下をくぐり抜けてしまう。
 これを防ぎたい場合は、兄stickyの代わりに親要素にposition:fixed;overflow:auto;top:hogeを指定し、兄はtop:0にする。

3. href=#idはjsで補う。

 stickyとhref=#idの相性は悪い。
 ページ下部の一族を表示している時にページ上部の一族へjumpすると、妹が兄貴に隠れてしまう。
 header(fixed)+article(absolute)のケースと違い、
 margin-top:-25px;padding-top:25pxでは不十分なので、
 jsでlocation.href='#';location.href='#id'を並べ、そのついでに親要素.scrollBy(0,-25)で微調整するのが手っ取り早い。

サンプル

スクリーンショット 2020-03-06 22.09.52.pngスクリーンショット 2020-03-06 22.10.24.png

 上の画像のように、爺さん[例:2]からそのひ孫[例:2111]を常に綺麗に表示するsticky-list(上述した3つの観点を網羅)のサンプルコードは以下。
 href=#id機能は使わず、list表示のみを行いたい場合は、コメントアウトで挟んだ部分は削除可。

<meta charset=utf-8>
<style>
*{margin:0;padding:0;box-sizing:border-box}
ul{list-style:none}
#i1{position:fixed;left:20%;width:60%;top:20%;height:60%;overflow:auto;padding-bottom:300px}
#i1 ul ul{padding-left:50px}
#i1 li{z-index:1;line-height:25px}
#i1 li.t{position:sticky;z-index:9;top:0;background:#bbb}
#i1 li li.t{z-index:8;top:25px;background:#ccc}
#i1 li li li.t{z-index:7;top:50px;background:#ddd}
#i1 li li li li.t{z-index:6;top:75px;background:#eee}
/*****textbox*****/
#i3{position:fixed;left:20%;width:60%;top:80%;height:25px;line-height:25px;text-align:center}
/****************/
</style>
<body>
<ul><li id=i1><li id=i2></ul>
<script>
const i1=1,i2=2,i3=3,lm=3,um=333;
window.onload=st;
function st(){wa()/**/;wt()/**/}
function wa(){ih(i1,ml(0))}
function ml(n){var c='<ul>';for(var i=1;i<=lm;i++){var n2=(n*10+i);
c+='<li class=t id=l'+n2+'>'+n2+(n2<=um?'<li>'+ml(n2):'')}return c+'</ul>'}
function ih(n,c){id(n).innerHTML=c}
function id(n){return document.getElementById('i'+n)}
////////textbox///////
function wt(){ih(i2,'<textarea id=i'+i3+' onkeyup=oku() placeholder=1〜3333のIDを半角入力し改行></textarea>')}
function oku(){var n=gv(i3);if(0<n.indexOf('\n')){n=n.replace('\n','');id(i1).scrollTop=0;
location.href='#l'+n;id(i1).scrollBy(0,0-(n<10?0:n<100?25:n<1000?50:75));wv(i3,'')}id(i3).focus()}
function gv(n){return id(n).value}
function wv(n,v){id(n).value=v}
//////////////////////
</script>
</body>

メモ張にコピペしてdesktopに「stk.html」で保存。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0