0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Slickでスライド要素が1枚のときはスライドをしない

Last updated at Posted at 2023-07-03

Slickスライドを使っている時に、スライドが1枚の時だけレイアウトが崩れたのでその時の対応まとめ。

■ レイアウト概要

PC表示:3カラム表示で4枚目のカードから矢印が出てスライドする
スクリーンショット 2023-07-03 15.14.45.png

SP表示:1カラム表示で2枚目のカードから矢印が出てスライドする
スクリーンショット 2023-07-03 15.21.18.png

でも1枚の時は1枚で表示したい(スライド解除したい)

2枚以上入っている場合はレイアウトの崩れはないのですが、1枚になった瞬間崩れました....

崩れた部分

PC表示:横幅が極端に狭くなる
SP表示:左側に隠れていて何も表示されない

調整したこと

  1. スライドの枚数を取得する(JS)
  2. スライドの枚数が1枚だったら...の分岐を作る(JS)
  3. レイアウトの調整をする(css)

今回は.slide-oneというクラスでレイアウトを整え、
スライドが1枚だった時はスライドの親(ulなど)にこのクラスを付与するパターンです。

slide.css
/* pcの表示 */
.slide-one{
  display: block; /* 横幅が極端に崩れるなら、この記述。ここはinlineでもOK */
}

/* spの表示 */
@media (max-width: 768px) {
  .slide-one .slick-track{
    display: inline; /* ここはinlineじゃないと表示されない */
  }
}

※slickはdisplay:flexだと崩れる場合があるのであまり使わないようにするのがベスト。
※cssは状況に応じて変えてください。あくまでも一例です。

slide.js
  // スライドの枚数を取得する
  const slideLength = document.querySelectorAll('.slideCard .slideCard-list"').length;

  // スライドが1枚だったら...
  if(slideLength == 1){
    $('.slideCard').addClass('slide-one');
  }

HTMLはこんな感じ↓

index.html
<ul class="slideCard">
      <li class="slideCard-list">
        <h2 class="slidecard-list__ttl">コンテンツ01</h2>
        <p class="slidecard-list__txt">
          ここにテキストここにテキストここにテキストここにテキストここにテキストここにテキスト
        </p>
        <a href="#" class="slideCard-list__btn">詳細はこちら</a>
      </li>
      <li class="slideCard-list">
        <h2 class="slidecard-list__ttl">コンテンツ02</h2>
        <p class="slidecard-list__txt">
          ここにテキストここにテキストここにテキストここにテキストここにテキストここにテキスト
        </p>
        <a href="#" class="slideCard-list__btn">詳細はこちら</a>
      </li>
      <li class="slideCard-list">
        <h2 class="slidecard-list__ttl">コンテンツ03</h2>
        <p class="slidecard-list__txt">
          ここにテキストここにテキストここにテキストここにテキストここにテキストここにテキスト
        </p>
        <a href="#" class="slideCard-list__btn">詳細はこちら</a>
      </li>
    </ul>

サンプルソースコード

See the Pen Slickのslide要素が1枚のときはスライドしない by aya (@orange2929) on CodePen.

Slick調整は地味に大変...

Slickだけには止まりませんが、簡単に実装できる反面
細かい調整の際に地味に厄介な部分があるのがプラグインやライブラリの宿命なんのかもしれない...🤔

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?