HTMLの書き方
head終了タグ直前に自作のCSSを読み込みます。
<link rel="stylesheet" type="text/css" href="css/6-5.css">
body内にHTMLを記載します。
<header id="header">
<h1>Logo</h1>
</header>
<main id="container">
<section class="fixed">
<h2>Area 1</h2>
<!--/area1--></section>
<section class="fixed">
<h2>Area 2</h2>
<!--/area2--></section>
<section class="fixed">
<h2>Area 3</h2>
<!--/area3--></section>
<!--/main--></main>
<footer id="footer">
<small>© copyright.</small>
</footer>
body 終了タグ直前に jQuery、stickyfill.jsと、動きを制御する自作のJS の3 つを読み込みます。
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stickyfill/2.1.0/stickyfill.min.js"></script>
<!--自作のJS-->
<script src="js/6-5.js"></script>
CSSの書き方
#header{
position: fixed;/*Header固定*/
top:0;
height: 70px;/*高さ指定*/
z-index: 2;
width:100%;
background:#fff;/*背景色*/
}
#container{
position: relative;
z-index: 1;/*header とfooterを手前にするため数字を小さく*/
}
section.fixed{
position: -webkit-sticky;/*Safari*/
position: sticky;
top:70px;/*Header高さ分で止まるようにする*/
padding: 600px 0;/*デモ画面の高さを持たすための上下余白*/
}
section.fixed:nth-child(odd){
background:#666;/*デモ画面の奇数背景色*/
}
section.fixed:nth-child(even){
background:#333;/*デモ画面の偶数背景色*/
}
section.fixed:last-of-type{
padding-top:70px;
/*最後のセクションだけ止まらないため、エリア内の情報が少ない時は、Header分の高さをpadding-topに追加して上部が見えるようにする*/
}
#footer{
position: relative;
z-index: 2;
}
/*=====タブレット以下の見え方 =====*/
@media screen and (max-width:768px){
section.fixed{
position:relative!important;/*sticky解除*/
top:0;/*70px⇒0pxに戻す*/
}
section.fixed:first-of-type{
padding-top:100px;
/*最初の要素は上部にHeaderの高さ以上の余白をとる*/
}
}
JSの書き方
768px以下では紙芝居風を解除するため、position: sticky;に対応していないブラウザ対応用のJavaScriptを、768pxより大きい場合に読み込む。
$(window).on('load resize', function() {
var windowWidth = window.innerWidth;
var elements = $('.fixed');
if (windowWidth >= 768) {
Stickyfill.add(elements);
}else{
Stickyfill.remove(elements);
}
});