7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

viewport幅いっぱいの横スクロールでアイテムの開始位置がコンテンツ幅と揃うやつをCSSで作る

7
Posted at

表題通り、viewport幅いっぱいの横スクロールでアイテムの開始位置がコンテンツ幅と揃うやつをCSSで作ります。

JSで作り込まれたライブラリを使うか、ブラウザがもともと備えている機能をベースに実装するか迷いどころですが、ループが不要ならばCsserな自分はできるだけ手作りするぞという感じです。

以下は今回の最終的なコードで、こういったものをベースにして必要に応じてJSで前次ボタンやインジケーターを実装したりします。

詳しい解説はデモに書いてますので、CSSが好きな方はご参考に。

デモ

.horizontal-scroller-4 {
    --real-content-width: min(
      var(--content-width),
      var(--client-width) - var(--gutter) * 2
    );
    --offset-x: calc(
      (var(--client-width) - var(--real-content-width)) / 2
    );
    
    margin-inline-start: calc(-1 * var(--offset-x));
    padding-inline: var(--offset-x);
    width: var(--client-width);
    height: 200px;
    display: flex;
    gap: var(--gutter);
    overflow-x: auto;
    scroll-snap-type: x mandatory;
    scroll-padding-inline-start: var(--offset-x);
}

.horizontal-scroller-4 > * {
    flex-shrink: 0;
    scroll-snap-align: start;
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?