🖥️

MUIでAspectRatioするだけ

2025/01/14に公開

概要

Chakra UIには、iframeの縦横比をいい感じにしてくれるコンポーネント AspectRatio がある。
https://www.chakra-ui.com/docs/components/aspect-ratio

ではMUIではどうかというと、MUI本体にはなくJoy UIの方に存在する。
https://mui.com/joy-ui/react-aspect-ratio/?srsltid=AfmBOoqlsSOkN0-DACXO7gvXaGl4QB4jKufchlaLrYjS8QePc6wWSNLM

とはいえMUIをシンプルに使っていたところわざわざこれだけのためにJoi UIを導入するのも気が引ける。

↓同じような悩みを抱えている人も見つけた
https://stackoverflow.com/questions/77707474/responsive-image-sizing-in-react-with-material-ui-how-to-dynamically-adapt-imag

実装

CSSの aspect-ratio プロパティを直接使えばシンプルに解決できた。

https://developer.mozilla.org/ja/docs/Web/CSS/aspect-ratio

aspect-ratio.tsx
<Box
    sx={{
        width: "800px",
        aspectRatio: "16 / 9",
        "& iframe": {
            width: "100%",
            height: "100%",
        },
    }}
>
        <iframe src={`https://www.youtube.com/embed/${id}`} allowFullScreen />
</Box>

ネットの古い記事だと padding-top: 56.25% で頑張っているものもまだ散見されるが、

Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2021.

らしいのでこっちを使っていきましょう。

Discussion