WEB

【CSS】フリック操作に対応したカルーセルの作成

scroll-snap-typeプロパティを使用した、フリック操作に対応したカルーセルの作成方法です。scroll-snap-typeを使用すればcssのみで実現可能です!

HTML

<div class="container">
  <ul>
    <li>ITEM01</li>
    <li>ITEM02</li>
    <li>ITEM03</li>
    <li>ITEM04</li>
    <li>ITEM05</li>
  </ul>
</div>

 

CSS

.container ul {
  display: grid;
  grid-template-columns: repeat(5, 100%);
  scroll-snap-type: x mandatory;
  overflow-x: auto;
}

.container ul li {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 450px;
  list-style: none;
  scroll-snap-align: start;
}

.container ul li:nth-of-type(1) {
  background: #fbdd74;
}

.container ul li:nth-of-type(2) {
  background: #ff6e6c;
}

.container ul li:nth-of-type(3) {
  background: #67568c;
}

.container ul li:nth-of-type(4) {
  background: #078080;
}

.container ul li:nth-of-type(5) {
  background: #232323;
}

  
▼CodePen
こちらにコードを書きました。

 

参考サイト

こちらの記事を参考にさせていただきました。
▼grid-template-columns – CSS: カスケーディングスタイルシート | MDN
https://developer.mozilla.org/ja/docs/Web/CSS/grid-template-columns

▼scroll-snap-type – CSS: カスケーディングスタイルシート | MDN
https://developer.mozilla.org/ja/docs/Web/CSS/scroll-snap-type

  

N.T
平日はコーディング、週末は子供と公園を走り回っています。