≪ Today I learned.
RSS購読
    公開日
    タグ
    CSS
    著者
    ダーシノ

    interpolate-sizeとcalc-size()のアニメーションの仕方と使い分け

    CSSアニメーションの鬼門に、height: autoのトランジションがうまくできない問題がある。

    calc-size()

    以前紹介したheight:0→autoをトランジションするでは、Experimentalなcalc-size()という関数をつかって実現していた。

    .panel {
      transition: height .5s;
      height: 0;
    
      &.expanded {
        height: calc-size(auto);
    
        /**
         * 固定値を使うことでトランジションできるが、内包するコンテンツによってはスタイルが崩れる
         * height: 500px;
         *
         * そもそもトランジションしない
         * height: auto;
         */
      }
    }

    内在サイズを数値に変換した結果を返す関数で、calc-size(auto)500pxのように実際の値を計算し、トランジションを可能にしていた。ただし、計算を伴うので複数要素への適用や頻繁な状態変更にはパフォーマンスの懸念があった。

    interpolate-size

    interpolate-sizeプロパティは、アニメーションやトランジションを行うときに、実際のheightなどのサイズとauto、fit-content、max-content などの内在サイズを補間するために使用する。

    ※interpolate…[動]補完する、内挿する

    取りうる値は以下の2つ。

    :root {
      interpolate-size: allow-keywords;
    }
    
    .panel {
      transition: height .5s;
      height: 0;
      
      &.expanded {
        height: auto;
      }
    }

    デモ

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

    関連: