LoginSignup
2
2

More than 1 year has passed since last update.

【初心者でもわかる】Twitter広告のような画像を横に並べるスライドショーをCSSだけで作る方法

Posted at

どうも7noteです。Twitterの広告で、画像を横に並べて一枚ずつスライドできるスライドショーを見かけたので、同じようなものをCSSで再現していきます。

sanple.gif

ソース

index.html
<div class="box">
  <section>1</section>
  <section>2</section>
  <section>3</section>
  <section>4</section>
  <section>5</section>
</div>
style.css
.box {
  width: 300px;  /* 適度な幅を指定 */
  height: 300px; /* 適度な高さを指定 */
  scroll-snap-type: x mandatory; /* スクロールスナップの指定 */
  overflow-x: scroll;            /* はみ出た部分をスクロールできる要素にする */
  display: flex; /* 要素を横並びにする */
}

.box section {
  scroll-snap-align: start; /* スクロールスナップの指定 */
  width: 200px;  /* 適度な幅を指定 */
  height: 200px; /* 適度な高さを指定 */
  text-align: center; /* 文字を左右中央にするため */
  line-height: 200px; /* 文字を上下中央にするため */
  flex: none;         /* 自動伸縮をさせない */
}

.box section + section {
  margin-left: 10px; /* 要素間に余白をとる */
}

.box section:nth-of-type(even) {
  background: #ccc; /* 偶数番の背景色 */
}
.box section:nth-of-type(odd) {
  background: #aaa; /* 奇数番の背景色 */
}

解説

JavaScript不使用で作ります。

scroll-snap-type: x mandatory;が今回のキーになるプロパティです。
これを指定することで、要素の左端に合わせてスクロール量を自動的に調整することができます。

あとは装飾的なCSSばかりですが、flexboxを使った横並びと、nth-childで色分けをして見やすくしたら完成です。

まとめ

身近にあるものの作りをどうやって作るかは普段から意識しています。
こういうものを作りたいと言われた時に、即答で「できますよ。」と答えられるとカッコいいから。

でもただ単純に新しい技術を身につけてみたいという欲が強いだけかもしれないです。
きっとこの記事を読んでいる方にもそういう方が多いのかなと思いますのでぜひほかの記事も読んでみてください。実用的なことからしょうもないCSSまでいろいろ書いています↓

参考:
https://qiita.com/drafts/eeba93e0275d8419f50b/edit
https://www.mitsue.co.jp/knowledge/blog/frontend/202102/02_1740.html
https://developer.mozilla.org/ja/docs/Web/CSS/scroll-snap-type

おそまつ!

~ Qiitaで毎日投稿中!! ~
【初心者向け】WEB制作のちょいテク詰め合わせ

2
2
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
2
2